简体   繁体   English

如何将由自动递增创建的一个表中的主键作为外键插入第二个表中?

[英]How to insert primary key from one table which created by auto increment, into a second table as forign key?

This is part of my code, which I insert data into two tables. 这是我的代码的一部分,我将数据插入两个表中。 Tables primary key is defined as auto increment:: song table PK is song_id. 表的主键定义为自动递增::歌曲表PK是song_id。 file table PK is File_id. 文件表PK是File_id。 I want to insert into file table the song_id as FK. 我想将song_id作为FK插入文件表。 How should I do it? 我该怎么办? Thanks 谢谢

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 provides the LAST_INSERT_ID() function which returns the last value of an autoincrement column. MySQL提供了LAST_INSERT_ID()函数,该函数返回自动增量列的最后一个值。 To use it you would perform one INSERT , SELECT the function's value, and INSERT the returned value into the second table. 要使用它,你将执行一个INSERTSELECT函数的值, INSERT返回值到第二个表。

You should also be using prepared statements instead of dynamic SQL for a plethora of reasons which I won't go into here. 出于多种原因,您也应该使用准备好的语句而不是动态SQL,我将在这里不作介绍。

I'm not terribly comfortable with C#, but I'll give it a shot: 我对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);
}

That's probably riddled with syntax errors, but should give you enough of an outline to get started. 这可能充满语法错误,但是应该给您足够的轮廓以开始使用。

Also, you really should wrap the entire operation (two INSERT s and a SELECT ) in a transaction, but I leave that as an exercise for the reader. 另外,您确实应该将整个操作(两个INSERTSELECT )包装在一个事务中,但是我将其作为练习留给读者。

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

相关问题 插入到两个表中,其中一个表具有自动增量主键,并且同一键用作另一表中的外键 - 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 do I insert an empty row in a table with an auto-Increment primary key? C#/ SQLCE CREATE TABLE以编程方式(自动增量+主键) - C#/SQLCE CREATE TABLE programmatically (Auto increment + Primary key) 如何插入一个具有自动增量编号作为主键的新记录? - How to insert a new record which has a auto increment number as primary key? 如何从表中获取主键而不进行第二次旅行? - How to get the primary key from a table without making a second trip? 如何设置带有修订的自动增量主键的表结构? - How do you setup table structure for auto increment primary key with revision? 主键自动递增为-1,-2,-3 - Primary key auto increment as -1,-2,-3 主键自动递增 - Primary key auto increment 将生成的主键作为外键插入控制器的不同表中 - Insert generated primary key as foreign key in different table from controller 如何将一个表中的主(代理)键添加到另一个表的外键中? - How to add a primary (Surrogate) key from one table into a foreign key of another table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM