在回答的问题中将commandtext转换为字符串问题

时间:2011-04-04 20:11:37

标签: c# asp.net mysql

问题与这篇文章有关,我认为他离线了,所以我无法得到任何反馈: MySql and inserting last ID problem remains 我不确定我是完全失明但是在这段代码中:

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

id没有设置为任何内容,我不确定他是如何尝试将其设置为最后插入的ID?

修改

int id = Convert.ToInt32(cmd.ExecuteScalar());
Label10.Text = Convert.ToString(id);

1 个答案:

答案 0 :(得分:1)

您应该能够使用select @@IDENTITY;返回插入记录的ID,而不必使用第二个查询:

 OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); select @@IDENTITY;"
 int id = Convert.ToInt32(cmd.ExecuteScalar());

在审核了您的旧问题之后,这应该是相同的:

 OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); SELECT LAST_INSERT_ID();"
 int id = Convert.ToInt32(cmd.ExecuteScalar());