我正在使用带有C#的MySQL,但我遇到了问题。为什么这段代码不起作用?
MySqlCommand cmd = new MySqlCommand("myConnectionString");
MySqlParameter lastId = new MySqlParameter();
lastId.ParameterName = "@LastID";
lastId.Value = 0;
lastId.Direction = System.Data.ParameterDirection.Output;
this.Command.Parameters.Add(lastId);
this.Command.CommandText = "SET @LastID = LAST_INSERT_ID();";
// 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 '0 = LAST_INSERT_ID()'
this.Command.ExecuteNonQuery();
答案 0 :(得分:2)
由于种种原因,上述代码完全错误。
所以
using(MySqlConnection con = new MySqlConnection("myConnectionString"))
using(MySqlCommand cmd = con.CreateCommand());
{
con.Open();
// BUILD an unique string with the INSERT INTO
// followed by the SELECT (with semicolon to divide)
string sqlInsertText = @"INSERT INTO yourTable (field1, FieldX) VALUES (value1, ValueX);
SELECT LAST_INSERT_ID();";
cmd.CommandText = sqlInsertText;
// ExecuteScalar will execute the text of the command and returns the first column of the
// first row retrieved by the last statement executed
// (in this case the result of SELECT LAST_INSERT_ID()
object result = cmd.ExecuteScalar();
if(result != null)
{
int lastID = Convert.ToInt32(result);
.....
}
}