2017-05-14 201 views
0

我有一个按钮,每次单击此按钮时,只要我向文本框中引入的文本不在数据库中,就会将新行添加到数据库中。否则,我会收到错误信息像主键一样,重复键是(“我成功添加到数据库中的最后一行”)。当我单击按钮后,即使我在文本框中引入的文本不在数据库,我必须重新启动该程序,然后again..whats问题?将数据添加到数据库中

private void button2_Click(object sender, EventArgs e) 
{ 
     DataRow rows = ds.Tables[0].NewRow(); 
     //this is primary key 
     rows[2] = textBox4.Text; 
     ds.Tables[0].Rows.Add(rows); 
    try 
    { 
     //updating database. 
     objConnect.UpdateDatabase(ds); 
     MessageBox.Show("Record Saved"); 
    } 
    catch (Exception err) 
    { 
     MessageBox.Show(err.Message); 
    } 
} 
+0

听起来像objConnect.UpdateDatabase试图插入而不是更新?但我们无法知道该方法在做什么。 – Crowcoder

+0

这里是类https://jsfiddle.net/o1cd14xv/ – RTX

+0

尝试运行简单的更新命令而不是使用数据适配器,您正在向数据集添加行并尝试更新它,但是在更新后您不刷新数据集。 – Krishna

回答

0

您可以使用以下语法重新编写代码。有很多复杂的方法是可用的,但因为你是初学者到C#,我认为这对你最好学习。

// Create connection object 

    SqlConnection connection = new SqlConnection("ConnectionStringtoYourDB"); 

    SqlCommand command = connection.CreateCommand(); 

    try { 

     // Open the connection. 

     connection.Open(); 

     // Execute the insert command. 

     command.CommandText = String.Concat("INSERT INTO Your_Tbl(FirstName) VALUES('", textBox4.Text,"')"); 

     command.ExecuteNonQuery(); 
     MessageBox.Show("Record Saved"); 

    } 
catch (Exception err) 
    { 
     MessageBox.Show(err.Message); 
    } 
    finally { 

     // Close the connection. 

     connection.Close(); 

    } 
0

我会建议先检查,看看是否在关键的表存在,如不及时补充,并得到新的主键,如果存在,那么做无非通知用户等。

在这里我有一个医院科室的表格(只有两列来保持简单)。

这里我使用一个类来保持数据操作与表单分离。

using System; 
using System.Data.SqlClient; 

namespace WindowsFormsApplication1 
{ 
    public class Operations 
    { 
     /// <summary> 
     /// Replace with your SQL Server name 
     /// </summary> 
     private string Server = "KARENS-PC"; 
     /// <summary> 
     /// Database in which data resides, see SQL_Script.sql 
     /// </summary> 
     private string Catalog = "ForumExamples"; 
     /// <summary> 
     /// Connection string for connecting to the database 
     /// </summary> 
     private string ConnectionString = ""; 
     /// <summary> 
     /// Setup the connection string 
     /// </summary> 
     public Operations() 
     { 
      ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"; 
     } 
     public bool InsertDepartment(string pDepartment, ref int pIdentifier) 
     { 
      using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString }) 
      { 
       using (SqlCommand cmd = new SqlCommand { Connection = cn }) 
       { 
        cmd.CommandText = "SELECT Name FROM Departments WHERE Name = @Name"; 
        cmd.Parameters.AddWithValue("@Name", pDepartment); 

        cn.Open(); 
        if (cmd.ExecuteScalar() == null) 
        { 
         cmd.CommandText = @" 
         INSERT INTO dbo.Departments (Name) 
         VALUES (@Name); SELECT CAST(scope_identity() AS int);"; 
         pIdentifier = Convert.ToInt32(cmd.ExecuteScalar()); 
         return true; 
        } 
        else 
        { 
         return false; 
        } 
       } 
      } 
     } 
    } 
} 

表格代码,一个按钮,一个文本框

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (!string.IsNullOrWhiteSpace(txtDepartmentName.Text)) 
     { 
      int id = 0; 
      Operations ops = new Operations(); 
      if (ops.InsertDepartment(txtDepartmentName.Text, ref id)) 
      { 
       MessageBox.Show($"Id for '{txtDepartmentName.Text}' is {id}"); 
      } 
      else 
      { 
       MessageBox.Show($"Department '{txtDepartmentName.Text}' is already in the database table"); 
      } 
     } 
     else 
     { 
      MessageBox.Show("Please enter a department name"); 
     } 
    } 
} 

上面的代码的某些部分是用于SQL - 服务器例如MS-Access或其他数据库可以通过一些修改来获取新的主键。