2013-06-12 47 views
-2

我是非常非常新的編程(大約一個星期),我目前正在做一個項目上的C#,SQL爲了大學。到目前爲止,我已經做得很好,並且能夠從Visual Studio窗體添加,刪除和更新到mysql的行。當我點擊添加按鈕時,我想要一個標籤(label5)用來自新插入行的新ID代碼進行更新。所以我可以拿走那個數字並繼續進行一些編程工作。將數據從C#表單(Visual Studio)添加到MySQL數據庫,並需要檢索新的記錄ID形式

繼承人我的代碼當我點擊那個按鈕..我一直在這5個小時,並用盡了在線資源(或者我只是不明白那些資源,我拿起像LastInsertedID,但它只是沒有工作對我來說)

private void button4_Click(object sender, EventArgs e) 
    { 

     string constring = "datasource=localhost;port=***;username=***;password=***"; 
     string Query = "insert into cars.customers (FirstName, Surname,TelephoneNo,Address1, Address2, Town, PostCode) values('" + this.FName_txt.Text + "','" + this.Surname_txt.Text + "','" + this.TelNo_txt.Text + "','" + this.Address1.Text + "','" + this.Address2.Text + "','" + this.Town_txt.Text + "','" + this.PostCode_txt.Text + "');"; 
     MySqlConnection conDataBase = new MySqlConnection(constring); 
     MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase); 
     MySqlDataReader myReader; 

     try 
     { 
      conDataBase.Open(); 
      myReader = cmdDataBase.ExecuteReader(); 
      MessageBox.Show("Saved Customer Details"); 
      while (myReader.Read()) 
      { 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

我明白我的術語是相當嚴峻的,所以我希望這是可以理解的 白癡指南是優選的,謝謝!

+0

運行'last_insert_id'命令。 –

回答

2

您可以抓取command.LastInsertedId

MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase); 
cmdDataBase.ExecuteNonQuery(); 
var lastId = cmdDataBase.LastInsertedId; 

// Assign to label 
label5.Text = lastId.ToString(); 
+0

非常感謝你! - 完美的作品 – Boo

+0

今天接受你的答案,晚些時候再好不過了! (抱歉!) – Boo

相關問題