使用C#更新mySQL表 [英] update a mySQL table using C#

查看:235
本文介绍了使用C#更新mySQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :

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");
}

推荐答案

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

Change your try section to the code below:

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部分时,将立即放置命令对象,并隐式关闭并放置连接对象.

The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.

这篇关于使用C#更新mySQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆