Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - MySql and inserting last ID problem remains

Ok after much reading and trying I still cant seem to get this to work:

      OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); SELECT LAST_INSERT_ID();", cn);

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

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

Tables:

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

Running in debug mode I get errors on this line,

            using (OdbcDataReader reader = cmd.ExecuteReader())

and,

cmd.ExecuteNonQuery();

Mysql is saying its a syntax error on this line SELECT LAST_INSERT_ID();", cn); but from what ive read this is legal.

Exact Error:

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

EDIT: Justins method:

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.
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Clarification, the mySQL .net ODBC driver doesn't allow multiple commands to be run like you are describing. You have to make two separate calls and wrap them in a transaction.

// 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.
              }
         }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...