为什么当我这样做时发生以下异常,我犯了什么错误? 将元组插入带AUTO_INCREMENT字段的表的正确方法是什么? 如何删除,是否可以更新ID?在MYSQL中使用AUTO_INCREMENT
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)
THX。我后来发现你也可以这样做: string s1 =“INSERT INTO projectinfo.student VALUES(NULL,\'john \')”; string s2 =“INSERT INTO projectinfo.student VALUES(NULL,\'mary \')”; – yeeen 2010-01-02 16:59:03
是的,你也可以这样做,你甚至可以通过执行SELECT * FROM [tab] WHERE [auto inc column] IS NULL来选择新插入的记录。 但是,为了清晰明了,我建议不要这样做。国际海事组织只是奇怪你明确地分配NULL,但实际上得到一个新生成的值,而不是。 – 2010-01-02 19:02:45