我如何知道以下 INSERT
查询是否成功?
MySqlConnection connection = new MySqlConnection(ConnectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("INSERT INTO People (PersonName, dateAdded) VALUES (?name, NOW())", connection);
command.Parameters.Add(new MySqlParameter("name", Name));
MySqlDataReader Reader = command.ExecuteReader();
我尝试运行 Reader.Read()
但只返回一个空字符串。谢谢。
最佳答案
您改为使用 ExecuteNonQuery
:
int affectedRows = command.ExecuteNonQuery();
if (affectedRows <= 0)
{
// Houston, we have a problem.
}
请记住,如果您对数据有触发器,它可能不会反射(reflect)您尝试INSERT
的实际行数:
You can use
ExecuteNonQuery
to perform any type of database operation, however any resultsets returned will not be available. Any output parameters used in calling a stored procedure will be populated with data and can be retrieved after execution is complete. ForUPDATE
,INSERT
, andDELETE
statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is-1
.
但是,一般来说,您会收到一个 MySqlException
如果您的查询遇到错误。
关于c# - 如何知道查询是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607302/