简体   繁体   English

如何在C#Windows窗体中使用LAST_INSERT_ID()?

[英]How to use LAST_INSERT_ID() in c# windows form?

In database I have three tables- 在数据库中,我有三个表-

patient(patientID,fName,lName) 
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)

patientID and diseaseID are index. patientIDdiseaseID是指数。 So on in c# I have three textboxes fNameTxt and lNameTXT , diseaseTxt .I want to store the name in patient table and disease name in illness table. 因此,在C#中我有三个文本框fNameTxtlNameTXTdiseaseTxt 。我想的名字存储在表疾病患者平台和疾病名称。 Besides, I have to record patientID and diseaseID in patientDisease table as well. 此外,我必须记录patientIDdiseaseIDpatientDisease表也是如此。 For patient table, I used following code. 对于患者表,我使用了以下代码。 I knew, I can use 我知道,我可以使用

SET @variable = LAST_INSERT_ID()

to get the id, but realised c#(visual studio) doesnt recognize it. 获取ID,但意识到C#(Visual Studio)无法识别它。 Basically, I couldnt make the overall statement. 基本上,我无法做出整体陈述。 Could anybody help me to get through this condition please. 有人可以帮我解决这个问题吗?

string connStr = @"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;

MySqlCommand cmd = conn1.CreateCommand();

cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)" 
    + "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();

I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it. 我在这里搜索了其他一些问题,但它们几乎与建议使用LAST_INSERT_ID()而不是如何使用它有关。

You can use this to get the last inserted id: 您可以使用它来获取最后插入的ID:

"SELECT * FROMtable(column) WHERE id = last_insert_id();

And use this if you want to insert a last id: 如果要插入最后一个ID,请使用以下代码:

"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";

Hope this might be useful. 希望这可能有用。

It will be much better if you use stored procedures 如果使用存储过程会更好

     INSERT INTO patient (patientID,patientID,lName)
            VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
   SET @last_id_in_patient  = LAST_INSERT_ID();        
     INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
            VALUES( @last_id_in_patient ,NULL,'text');  # use ID in second table";

Now You can update your PatientDisease table for particular PatientId. 现在,您可以为特定的PatientId更新PatientDisease表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM