我正在使用
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
举个例子:
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val2')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
正确地将Command successful
添加到textbox1。
但是当我将sometable
更改为sometablee
时,textbox1会保持为空。我希望它通知我命令失败(sometablee
不存在),但它没有。
谁能告诉我为什么?
完整代码:
mysql_command:
class mysql_command
{
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
}
的mysql_connect:
class mysql_connect
{
private MySqlConnection connection = null;
public MySqlConnection connect(string server, string database, string UID, string password)
{
try
{
string MyConString = "SERVER=" + server + ";" +
"DATABASE=" + database + ";" +
"UID=" + UID + ";" +
"PASSWORD=" + password + ";";
connection = new MySqlConnection(MyConString);
connection.Open();
}
catch (Exception ex) { Console.WriteLine("MySQL connect error : "+ex.Message); }
return connection;
}
public void disconnect()
{
connection.Close();
}
}
用法:
private void Form1_Load(object sender, EventArgs e)
{
mysql_connect con = new mysql_connect();
MySqlConnection connection = con.connect("server1.x.x", "somedb", "user", "pass");
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val1')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
}
答案 0 :(得分:1)
原因如我所料,您将在命令方法中获得异常,
public static bool command(string input, MySqlConnection con)
因为请求的表不存在,.... 编辑命令方法以处理异常:
public static bool command(string input, MySqlConnection con)
{
try
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
catch
{}
return false;
}