【发布时间】:2016-06-23 16:24:11
【问题描述】:
我是 C# 新手,但我正在开发一个简单的 GUI 来管理我的 mysql 数据库。 我需要保持连接打开直到程序结束(当我关闭它时),但是在单击连接按钮后,我插入了一些数据,但程序显示“连接必须有效且打开”。你能帮帮我吗?
namespace MysqlConn
{
public partial class Form1 : Form
{
private static MySqlConnection conn;
MySqlCommand mcd;
private void button1_Click(object sender, EventArgs e)
{
GetConn();
}
public static MySqlConnection GetConn()
{
conn = new MySqlConnection("datasource=localhost;port=3306;username='+UserName'; password= '+PassWord'");
MessageBox.Show("OK..");
return conn;
}
public Form1()
{
InitializeComponent();
String DataBase = textBoxDb.Text;
String UserName = textBoxUserName.Text;
String PassWord = textBoxPassword.Text;
}
public void openCon()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
public void closedConn()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
public void executeQuery(String s)
{
try
{
mcd = new MySqlCommand(s, conn);
if (mcd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query executed");
}
else
{
MessageBox.Show("Query not executed");
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
} finally
{
}
}
private void buttonInsert_Click_1(object sender, EventArgs e)
{
string s = "insert into prova_csharp.users (Name, Surname, Age) values ('"+textBoxName.Text+"', '"+textBoxSurname.Text+"', '"+textBoxAge.Text+"')";
executeQuery(s);
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
string s = "update prova_csharp.users set Name='" + textBoxName.Text + "', Surname='" + textBoxSurname.Text + "', Age=" + textBoxAge.Text + " where Id=" + textBoxId.Text;
executeQuery(s);
}
private void buttonDelete_Click(object sender, EventArgs e)
{
string s = "delete from prova_csharp.users where Id = " + textBoxId.Text;
executeQuery(s);
textBoxId.Text = "";
}
}
}
【问题讨论】:
-
嗯,您打开连接的唯一地方是
openCon()内部,并且永远不会被调用。 -
这个错误似乎很容易解释。我建议连接未打开,因为我看不到您实际调用
openCon或以其他方式调用conn.Open的任何地方。 -
另外,请确保您使用参数化查询。这些是经典的 sql 注入,在这样的插入中使用用户输入(文本框)。完成后在该连接上调用 Dispose。