[英]Using AUTO_INCREMENT in MYSQL
為什么這樣做時會出現以下異常,我犯了什么錯誤? 將元組插入具有AUTO_INCREMENT字段的表中的正確方法是什么? 如何刪除,是否可以更新ID?
string connStr = "server=localhost;user=root;database=test;port=3306;password=XXX;";
MySqlConnection conn = new MySqlConnection(connStr);
try{
MessageBox.Show("Hello");
conn.Open();
string s0 = "CREATE TABLE school.student ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(45) NOT NULL, PRIMARY KEY (id))";
string s1 = "INSERT INTO school.student VALUES ( LAST_INSERT_ID(), \'john\' )";
string s2 = "INSERT INTO school.student VALUES ( LAST_INSERT_ID(), \'mary\' )";
MySqlCommand cmd = new MySqlCommand(s0, conn);
cmd.ExecuteNonQuery();
cmd = new MySqlCommand(s1, conn);
cmd.ExecuteNonQuery();
cmd = new MySqlCommand(s2, conn);
cmd.ExecuteNonQuery();
conn.Close();
}catch(Exception ex){
TextWriter tw = new StreamWriter("C:\\test.txt");
MessageBox.Show(ex.ToString());
tw.WriteLine(ex.ToString());
}
MySql.Data.MySqlClient.MySqlException: Duplicate entry '1' for key 'PRIMARY'
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.ReadResult()
at MySql.Data.MySqlClient.ResultSet.NextResult()
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at ProjectInfo.Connect.Exec(String commandName, vsCommandExecOption executeOption, Object& varIn, Object& varOut, Boolean& handled)
這些行是問題所在:
string s1 = "INSERT INTO school.student VALUES ( LAST_INSERT_ID(), \'john\' )";
string s2 = "INSERT INTO school.student VALUES ( LAST_INSERT_ID(), \'mary\' )";
請參見,LAST_INSERT_ID()函數返回最后生成的auto_increment值的值。 在第一次插入時,尚未發生任何插入,並且LAST_INSERT_ID()的計算結果為NULL。 假設您的表為空,則插入該行,其生成的值為1。在第二次插入時,由於您插入了上一行,因此LAST_INSERT_ID()將為1。 因此,這一次,db中已經存在一行,並且由於重復項1而導致第二次插入不成功。
像這樣重寫:
string s1 = "INSERT INTO school.student (name) VALUES (\'john\' )";
string s2 = "INSERT INTO school.student (name) VALUES (\'mary\' )";
只需省略具有AUTO_INCREMENT的字段,MySQL將負責其余的工作。 您可以在DELETE之后更新ID,但是我建議您不要這樣做。
您不應該嘗試在自動遞增字段中插入值-因為(提示中的提示是在名稱中)MySQL會自動將其遞增。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.