我正在用MySQL数据库在C#(Visual Studio 2017)中构建配置表单。我想在数据库中存储文件夹路径。我收到“连接必须有效且打开”错误,但是当我注释掉“ cmd2.ExecuteNonQuery();”时我没有得到错误。如果您能告诉我我做错了什么,我将不胜感激。如果您能给我一个代码示例,那也很好。这是我的代码:
private void button5_Click(object sender, EventArgs e)
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
string a = textBox1.Text;
string b = textBox2.Text;
string c = textBox4.Text;
string escapedPath = a.Replace(@"\", @"\\").Replace("'", @"\'");
string escapedPath1 = b.Replace(@"\", @"\\").Replace("'", @"\'");
string escapedPath2 = c.Replace(@"\", @"\\").Replace("'", @"\'");
MySqlCommand cmd2 = new MySqlCommand("update shopmanager.paths set path_to_clients = '" + escapedPath + "',path_to_employee = '" + escapedPath1 + "',path_to_procedures = '" + escapedPath2 + "';");
try
{
con.Open();
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
答案 0 :(得分:5)
当您注释掉cmd2.ExecuteNonQuery();
时,什么也没发生,所以不太可能出错;-)
连接必须有效且打开
此错误表明该命令没有绑定的打开连接对象。尽管您打开了连接,但从未将其分配给命令(不同的命令可能具有不同的连接)。
所以;您需要将连接分配给命令:
cmd2.Connection = con;
或更常见的是在构建命令时:
MySqlCommand cmd2 = new MySqlCommand("your sql goes here", con);
答案 1 :(得分:2)
连接必须有效且打开始终指示在执行MySqlCommand
方法或从未提供适当的ExecuteNonQuery()
实例时,MySqlConnection
与任何活动连接均未关联相应的命令,即使连接已经打开。
因此,最好设置您的UPDATE
查询,这样更易于阅读:
using (MySqlConnection con = new MySqlConnection(conSettings.ToString()))
{
using (MySqlCommand cmd2 = new MySqlCommand(@"update shopmanager.paths
set path_to_clients = @escapedPath, path_to_employee = @escapedPath1,
path_to_procedures = @escapedPath2 where ...", con))
{
cmd2.Parameters.AddWithValue("@escapedPath", a.Replace(@"\", @"\\").Replace("'", @"\'"));
cmd2.Parameters.AddWithValue("@escapedPath1", b.Replace(@"\", @"\\").Replace("'", @"\'"););
cmd2.Parameters.AddWithValue("@escapedPath2", c.Replace(@"\", @"\\").Replace("'", @"\'"));
try
{
con.Open();
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
或分别设置CommandText
和Connection
属性(也可以使用参数,完全避免串联值):
using (MySqlConnection con = new MySqlConnection(conSettings.ToString()))
{
using (MySqlCommand cmd2 = new MySqlCommand())
{
cmd2.Connection = con;
cmd2.CommandText = "update shopmanager.paths set path_to_clients = @escapedPath, path_to_employee = @escapedPath1, path_to_procedures = @escapedPath2 where ...";
cmd2.Parameters.AddWithValue("@escapedPath", a.Replace(@"\", @"\\").Replace("'", @"\'"));
cmd2.Parameters.AddWithValue("@escapedPath1", b.Replace(@"\", @"\\").Replace("'", @"\'"););
cmd2.Parameters.AddWithValue("@escapedPath2", c.Replace(@"\", @"\\").Replace("'", @"\'"));
try
{
con.Open();
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
请注意,using
语句对于成功更新后立即处置连接对象很有用。