MysqlException未处理C#LAST_INSERT_ID()

时间:2016-07-13 00:17:15

标签: c# winforms persistence

每当我添加这行时:SET @last_id_owner = LAST_INSERT_ID();.它给了我警告; MysqlException未在行中处理:cmd.ExecuteNonQuery(); 如果我删除它就行了。

String sql = "INSERT INTO owner (name,email,reward)"
             + " VALUES('" + owner.Name + "','" + owner.EMail + "'," + owner.Reward + ");SET @last_id_owner = LAST_INSERT_ID();";
connect();
MySqlCommand cmd = new MySqlCommand(sql, conexion);
cmd.ExecuteNonQuery();
disconnect();

我需要获取最后一个插入ID并在另一个表的插入中使用它。 怎么了?

2 个答案:

答案 0 :(得分:1)

您必须注意的第一件事是,您的查询将为SqLInjection打开一扇大门。要避免这种情况,您应该使用参数化查询。然后,您可以使用LastInsertedId类的MySqlCommand来获取最后插入的ID。您可以使用以下代码段来实现这两个目标:

// Parameterization implementation
String sql = "INSERT INTO owner (name,email,reward)"
    + " VALUES(@ownerName,@ownerMail,@ownerReward)";

MySqlCommand cmd = new MySqlCommand(sql, conexion);
cmd.Parameters.Add("@ownerName",MySqlDbType.VarChar).Value= owner.Name;
cmd.Parameters.Add("@ownerMail", MySqlDbType.VarChar).Value = owner.EMail;
cmd.Parameters.Add("@ownerReward", MySqlDbType.VarChar).Value = owner.Reward;

// Executing Query and getting last Inserted ID
cmd.ExecuteNonQuery();
long lastInsertedID = cmd.LastInsertedId;

答案 1 :(得分:0)

尝试使用此代码它将帮助您......如您所愿。

 String sql = "INSERT INTO owner (name,email,reward)  VALUES('" + owner.Name + "','" + owner.EMail + "'," + owner.Reward + "); select LAST_INSERT_ID();";
            connect();
            MySqlCommand cmd = new MySqlCommand(sql, conexion);
            cmd.ExecuteScalar();
            disconnect();