我有两个表,即父表和子表。现在我向父表插入一个值,其中包含自动增量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
答案 0 :(得分:2)
如果你想在child中插入一行,就在创建父行之后,你可以在下一个insert语句中使用last_insert_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();
答案 1 :(得分:1)