Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在父表中插入值时在子表中自动生成id_C#_Mysql - Fatal编程技术网

C# 在父表中插入值时在子表中自动生成id

C# 在父表中插入值时在子表中自动生成id,c#,mysql,C#,Mysql,我有两个表,即父表和子表。现在,我向父表插入一个值,具有自动递增id。代码如下: string query2 = "INSERT INTO printer_info(printer_ip) VALUES(@ipAddress)"; MySqlCommand cmd1 = new MySqlCommand(query2, connection); cmd1.Parameters.AddWithValue("@ipAddress", pAddress); cmd1.ExecuteNonQuery(

我有两个表,即父表和子表。现在,我向父表插入一个值,具有自动递增id。代码如下:

string query2 = "INSERT INTO printer_info(printer_ip) VALUES(@ipAddress)";
MySqlCommand cmd1 = new MySqlCommand(query2, connection);

cmd1.Parameters.AddWithValue("@ipAddress", pAddress);
cmd1.ExecuteNonQuery();
现在我的问题是,当值插入父表时。如果我想自动生成子表中的id,请告知

   ID | printer_ip               printer_id | page_count
   ---------------    ------>    -----------------------
    1 | 10.0.0.0                            |

   PRIMARY KEY ID                FOREIGN KEY printer_id
当显示父表中的新行时,可以使用在子表中添加新行

编辑


提示:这两个操作应该在单个事务中执行,以避免其中一个操作失败时出现不一致…

如果您也希望在子事务中插入一行,就在创建父行之后,您可以在下一个insert语句中使用
last\u insert\u id()

示例

string query2 = "INSERT INTO printer_info(printer_ip) VALUES(@ipAddress)";
MySqlCommand cmd1 = new MySqlCommand(query2, connection);

cmd1.Parameters.AddWithValue("@ipAddress", pAddress);
cmd1.ExecuteNonQuery();

string query_for_child_row = "INSERT INTO printer_queue(printer_id, page_count) 
                              VALUES( LAST_INSERT_ID(), @page_count )";
MySqlCommand cmd2 = new MySqlCommand( query_for_child_row, connection );

cmd2.Parameters.AddWithValue( "@page_count", page_count );
cmd2.ExecuteNonQuery();

提示:这两个操作应该在单个事务中执行,以避免其中一个操作失败时出现不一致……如果我们使用最后一个插入id,它将在子表的最后一个插入id之后插入id?表示未与父表同步。例如,如果父表中的id 1包含子表中的2个值计数,则子打印机的id不能像1,1。大概是1,2。如果我错了,请纠正我。如果new
parent\u id
'1'
,那么无论您在哪里调用该函数,但是,
'last\u insert\u id()'
都将返回相同的
'1'