2013-06-12 43 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

相关问题