![](/img/trans.png)
[英]Insert into two tables with one table having an auto increment primary key and that same key is used as a foreign key in another table
[英]How to insert primary key from one table which created by auto increment, into a second table as forign key?
这是我的代码的一部分,我将数据插入两个表中。 表的主键定义为自动递增::歌曲表PK是song_id。 文件表PK是File_id。 我想将song_id作为FK插入文件表。 我该怎么办? 谢谢
try
{
string MyConnection1 = "datasource=localhost;port=3306;username=root;password=123";
string Query1 = "insert into myproject.song " +
"(song_name, house_number, song_text) " +
"values " +
"('" + line1 + "', '" + paragraphs.Length +
"', '" + filetext + "');" + //Insert song name, song huose count and full song text
"insert into myproject.file " +
"(File_Location, Words_number, Lines_number, File_name, song_id) " +
"values " +
"('" + strfilename + "','" + words.Length + "','" +
totallineCnt + "', '" + fileNameOnly +
"', ?????????????;"; //Insert table file details
MySqlConnection myConn1 = new MySqlConnection(MyConnection1);
MySqlCommand MyCommand1 = new MySqlCommand(Query1, myConn1);
MySqlDataReader MyReader1;
myConn1.Open();
MyReader1 = MyCommand1.ExecuteReader();
while (MyReader1.Read())
{
}
myConn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
MySQL提供了LAST_INSERT_ID()
函数,该函数返回自动增量列的最后一个值。 要使用它,你将执行一个INSERT
, SELECT
函数的值, INSERT
返回值到第二个表。
出于多种原因,您也应该使用准备好的语句而不是动态SQL,我将在这里不作介绍。
我对C#不太满意,但我会试一试:
string MyConnection1 = "datasource=localhost;port=3306;username=root;password=123";
string Query1 = "insert into myproject.song " +
"(song_name, house_number, song_text) " +
"values " +
"(@SongName, @HouseNum, @SongText)"; //Insert song name, song huose count and full song full text
string Query2 = "SELECT LAST_INSERT_ID()";
string Query3 = "insert into myproject.file " +
"(File_Location, Words_number, Lines_number, File_name, song_id) " +
"values " +
"(@FileLoc, @WordCount, @LineCount, @FileName, @SongId"; //Insert the table file details
try
{
MySqlConnection myConn1 = new MySqlConnection(MyConnection1);
myConn1.Open();
MySqlCommand Cmd1 = new MySqlCommand(Query1, myConn1);
Cmd1.Parameters.AddWithValue("@SongName", line1);
Cmd1.Parameters.AddWithValue("@HouseNum", paragraphs.Length);
Cmd1.Parameters.AddWithValue("@SongText", filetext);
Cmd1.ExecuteNonQuery();
MySqlCommand Cmd2 = new MySqlCommand(Query2, myConn1);
object result = Cmd2.ExecuteScalar();
int songId = Convert.ToInt32(result);
MySqlCommand Cmd3 = new MySqlCommand(Query3, myConn1);
Cmd3.Parameters.AddWithValue("@FileLoc", strfilename);
Cmd3.Parameters.AddWithValue("@WordCount", words.Length);
Cmd3.Parameters.AddWithValue("@LineCount", totallineCnt);
Cmd3.Parameters.AddWithValue("@FileName", fileNameOnly);
Cmd3.Parameters.AddWithValue("@SongId", songId);
Cmd3.ExecuteNonQuery();
myConn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
这可能充满语法错误,但是应该给您足够的轮廓以开始使用。
另外,您确实应该将整个操作(两个INSERT
和SELECT
)包装在一个事务中,但是我将其作为练习留给读者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.