update a mySQL table using C#

前端 未结 2 1694
粉色の甜心
粉色の甜心 2021-01-24 04:29

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 fin

相关标签:
2条回答
  • 2021-01-24 05:07

    I don't see the connection being opened.

    Here is an example from MSDN: even inside a using block, they open the connection explicitly

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

    Edit: The principle is the same for MySQL as it is for SQL Server:

    public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection) 
    {
      MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
      myCommand.Connection.Open();
      myCommand.ExecuteNonQuery();
      myConnection.Close();
    }
    
    0 讨论(0)
  • 2021-01-24 05:16

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

    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.

    0 讨论(0)
提交回复
热议问题