2011-08-22 51 views
0

下面是代碼數據未使用dataadapter插入到sql數據庫..?

string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Inventory.mdf;Integrated Security=True;User Instance=True"; 
     SqlConnection con = new SqlConnection(constr); 
     try 
     { 
      SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Users", con); 
      DataSet ds = new DataSet(); 
      con.Open(); 
      SqlCommandBuilder cmd = new SqlCommandBuilder(sda); 
      sda.Fill(ds, "Users"); 
      DataRow row = ds.Tables["Users"].NewRow(); 
      row[0] = 2; 
      row[1] = txtUsername.Text; 
      row[2] = txtPassword.Text; 
      ds.Tables["Users"].Rows.Add(row); 
      int res=sda.Update(ds, "Users"); 
      con.Close(); 
      sda.Dispose(); 
      dgUser.ItemsSource = null; 
      dgUser.ItemsSource = ds.Tables["Users"].DefaultView; 
      ds.Dispose(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      if (con.State == ConnectionState.Open) 
       con.Close(); 
      con.Dispose(); 
     } 

問題是,它是沒有錯誤執行,但是當你在數據庫中檢查不會有記錄的插入......可能是什麼錯誤..?

+0

你是否檢查過ds獲取用戶的表記錄? – Syeda

+0

我試圖用我的表執行你的代碼,它工作正常。 –

+0

其實它沒有插入,但它可以顯示錶中的數據。 –

回答

0

說實話,我沒有看到代碼中的任何錯誤。您可以嘗試使用斷點進行調試,並在傳遞到數據庫之前查看該行是否已正確添加到數據集?

+0

是的..我也試過..數據集添加完美的行。 sda.update返回一行受到影響..但數據未添加到表中 –

0

您是否爲DataAdapter配置了InsertCommand?沒有設置它不太可能的適配器會知道插入你的記錄。

你需要設置此之後,像

cmd ="INSERT INTO ...."; // add param to this 

sda.InsertCommand = cmd 

嘗試更新。(同樣做了UpdateCommand的適配器如果需要的話)

+0

他正在使用SqlDataAdapter的Update方法。他不需要配置插入或更新命令。 –

+0

@nevayeshirazi我認爲這隻適用於使用'SelectCommand'的情況,否則你必須...... – V4Vendetta

+0

你說得對,我只是在MSND上看到它,但他的代碼在我的電腦上工作得很好。 –

1

嘗試做插入,而不是選擇

SqlDataAdapter sda = new SqlDataAdapter("insert into Users (ID, UserName, Password) VALUES (2," + 
     txtUsername.Text + ", " + txtPassword.Text + ")", con); 

但內聯SQL通常是一個壞主意。最好是寫一個存儲過程並執行你的代碼

+0

我也試過.. cmd.ExecuteNonQuerry()返回一行受到影響,但數據沒有插入到表 –

+0

當您在sql server management studio中使用相同的語法時,可以插入嗎?使用相同的登錄憑據 –