mysql 转换commandtext到字符串问题在回答的问题

brjng4g3  于 5个月前  发布在  Mysql
关注(0)|答案(1)|浏览(59)

与此相关的问题后,我认为他是离线虽然所以我不能得到任何反馈ATM:
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);

jjhzyzn0

jjhzyzn01#

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

OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); select @@IDENTITY;"
 int id = Convert.ToInt32(cmd.ExecuteScalar());

字符串
在回顾了你的旧问题之后,这应该是一样的:

OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('[email protected]'); SELECT LAST_INSERT_ID();"
 int id = Convert.ToInt32(cmd.ExecuteScalar());

相关问题