2017-05-14 244 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或其他數據庫可以通過一些修改來獲取新的主鍵。