MySql和插入最后一个ID问题仍然存在

时间:2011-04-04 19:00:28

标签: c# asp.net mysql

好好经过多次阅读和尝试,我似乎仍然无法让这个工作:

      OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); SELECT LAST_INSERT_ID();", cn);

cmd.ExecuteNonQuery();
                using (OdbcDataReader reader = cmd.ExecuteReader())
                {

                string theUserId = String.Format("{0}", reader.GetString(0));
                Label10.Text = theUserId;

表:

User
--------
UserID (auto increment, pk)
Email

在调试模式下运行我在这一行上出错了,

            using (OdbcDataReader reader = cmd.ExecuteReader())

cmd.ExecuteNonQuery();

Mysql在这一行SELECT LAST_INSERT_ID();",cn)上说它的语法错误;但是从我读过的内容来看,这是合法的。

确切错误:

ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1

编辑:Justins方法:

using (OdbcConnection connection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
    // ODBC command and transaction objects
    OdbcCommand command = new OdbcCommand();
    OdbcTransaction transaction = null;

    // tell the command to use our connection
    command.Connection = connection;

    try
    {
        // open the connection
        connection.Open();

        // start the transaction
        transaction = connection.BeginTransaction();

        // Assign transaction object for a pending local transaction.
        command.Connection = connection;
        command.Transaction = transaction;

        // TODO: Build a SQL INSERT statement
        OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", connection); 

        // run the insert using a non query call
        command.CommandText = cmd.ToString();
        command.ExecuteNonQuery();

        /* now we want to make a second call to MYSQL to get the new index 
           value it created for the primary key.  This is called using scalar so it will
            return the value of the SQL  statement.  We convert that to an int for later use.*/
        command.CommandText = "select last_insert_id();";
        id = Convert.ToInt32(command.ExecuteScalar());

        // the name id doesnt not exist in the current context

        // Commit the transaction.
        transaction.Commit();
    }
    catch (Exception ex)
    {
        Label10.Text = ": " + ex.Message;

        try
        {
            // Attempt to roll back the transaction.
            transaction.Rollback();
        }
        catch
        {
            // Do nothing here; transaction is not active.
        }
    }
}

3 个答案:

答案 0 :(得分:4)

澄清,mySQL .net ODBC驱动程序不允许像您描述的那样运行多个命令。您必须进行两次单独的调用并将它们包装在事务中。

// open a new connection using a default connection string I have defined elsewhere
using( OdbcConnection connection = new OdbcConnection( s_connectionString ) )
{
      // ODBC command and transaction objects
      OdbcCommand command = new OdbcCommand();
      OdbcTransaction transaction = null;

      // tell the command to use our connection
      command.Connection = connection;

      try
      {
           // open the connection
           connection.Open();

           // start the transaction
           transaction = connection.BeginTransaction();

           // Assign transaction object for a pending local transaction.
           command.Connection = connection;
           command.Transaction = transaction;

           // TODO: Build a SQL INSERT statement
           StringBuilder SQL = new StringBuilder();

           // run the insert using a non query call
           command.CommandText = SQL.ToString();
           command.ExecuteNonQuery();

           /* now we want to make a second call to MYSQL to get the new index 
              value it created for the primary key.  This is called using scalar so it will
               return the value of the SQL  statement.  We convert that to an int for later use.*/
           command.CommandText = "select last_insert_id();";
           id = Convert.ToInt32( command.ExecuteScalar() );

           // Commit the transaction.
           transaction.Commit();
     }
     catch( Exception ex )
     {
          Debug.WriteLine( ex.Message );

          try
          {
               // Attempt to roll back the transaction.
               transaction.Rollback();
            }
            catch
            {
                 // Do nothing here; transaction is not active.
              }
         }
}

答案 1 :(得分:0)

如果您的电子邮件是唯一的,则可以使用

Select ID From User where Email='rusty@msn.com'

你确信你总能得到正确答案。

如果您的电子邮件不是唯一的,则应使用锁定以确保仅在线程上执行查询,然后在插入后使用此查询

Select Max(ID) From User

答案 2 :(得分:0)

解决方法:

  1. 为您的查询添加一个out参数:
  2. 在查询内部使用SET @OpParam = SELECT LAST_INSERT_ID();
  3. 在你的代码中得到它好像((int)@ OpParam.Value> 0){pull out}。
  4. 此外,如果运行select而不是NonQuery,请使用ExecuteScalar()。
  5. 希望它对你有所帮助。