【发布时间】:2025-12-03 18:00:01
【问题描述】:
好的,经过大量阅读和尝试,我似乎仍然无法让它工作:
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
编辑:贾斯汀方法:
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.
}
}
}
【问题讨论】:
-
是否允许在 1 个
OdbcCommand中执行 2 个查询/语句?如果你在 2 个不同的地方做会发生什么? -
@Wrikken,这就是问题所在,.net mySQL ODBC 驱动程序不允许在该上下文中使用多个命令。您必须拨打两个单独的电话。我以前遇到过这个问题;)
-
尝试使用字符串而不是使用字符串和连接参数创建另一个 OdbcCommand 对象。然后将 command.CommandText 设置为该字符串。我认为当您创建第二个 OdbcCommand 对象时会发生一些奇怪的事情。