1

我编写了一些 C# 来更新 MySql 表,但每次调用 ExecuteNonQuery() 方法时都会出现异常。我在网上对此进行了研究,发现的每个解决方案都会产生相同的错误。我有一个与数据库的开放连接,并且对数据库的更新查询已正确写入。到目前为止,我提出的代码是:

public int executeUpdate()
{
  int result = 0;
  if (isConnected)
  {
    try
    {
      MySqlConnection cn = new  MySqlConnection(connection.ConnectionString);
      MySqlCommand cmd = new MySqlCommand();

      cmd.Connection = cn; 
      cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
      int numRowsUpdated = cmd.ExecuteNonQuery(); 
    }
    catch (MySqlException exSql)
    {
      Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
      Console.Error.WriteLine(exSql.StackTrace);
    }
    catch (Exception ex)
    {
      Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
      Console.Error.WriteLine(ex.StackTrace);
    }
  }
  else
    Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
4

2 回答 2

4

将您的尝试部分更改为以下代码:

try
{
    using(MySqlConnection cn = new  MySqlConnection(connection.ConnectionString))
    {        
        MySqlCommand cmd = new MySqlCommand();
        cmd.Connection = cn; 
        cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
        cn.Open();
        int numRowsUpdated = cmd.ExecuteNonQuery();
        cmd.Dispose(); 
     }
}

在执行命令之前必须打开连接。在上面的示例中,命令对象将立即被释放,而连接对象将在您离开 using 部分时隐式关闭和释放。

于 2012-04-25T21:10:48.353 回答
3

我没有看到正在打开的连接

这是来自MSDN的示例:即使在 using 块内,它们也会显式打开连接

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

编辑MySQL的原理与SQL Server 的原理相同:

public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection) 
{
  MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
  myCommand.Connection.Open();
  myCommand.ExecuteNonQuery();
  myConnection.Close();
}
于 2012-04-25T20:56:35.197 回答