【问题标题】:Using AUTO_INCREMENT in MYSQL在 MYSQL 中使用 AUTO_INCREMENT
【发布时间】:2009-12-24 11:27:28
【问题描述】:

为什么我这样做时会出现以下异常,我犯了什么错误? 将元组插入具有 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)

【问题讨论】:

    标签: mysql auto-increment


    【解决方案1】:

    这些是问题所在:

    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行了,第二次insert没有成功,因为1重复了。

    这样改写:

    string s1 = "INSERT INTO school.student (name) VALUES (\'john\' )";
    string s2 = "INSERT INTO school.student (name) VALUES (\'mary\' )";
    

    【讨论】:

    • 谢谢。后来我发现你也可以这样做:string s1 = "INSERT INTO projectinfo.student VALUES (NULL, \'john\')"; string s2 = "INSERT INTO projectinfo.student VALUES (NULL, \'mary\')";
    • 是的,您也可以这样做,您甚至可以通过执行 SELECT * FROM [tab] WHERE [the auto inc column] IS NULL 来选择新插入的记录。但是,为了清晰和明确起见,我建议不要这样做。 IMO 很奇怪,您明确分配 NULL 但实际上却获得了新生成的值。
    【解决方案2】:

    只需省略具有 AUTO_INCREMENT 的字段,MySQL 将处理其余部分。 您可以在 DELETE 之后更新 ID,但我建议您不要这样做。

    【讨论】:

      【解决方案3】:

      您不应该尝试在自动递增字段中插入值 - 因为(提示在名称中)这将由 MySQL 自动递增。

      【讨论】:

        猜你喜欢
        • 2012-06-30
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        相关资源
        最近更新 更多