我的 C# 代码有一点问题(我通常是 C++ 开发人员,所以我只知道 C# 的大部分基础知识)
我想编写一个类来使用该程序执行 SQL 查询,但 atm 它什么也不做,我也没有从中得到任何错误。
我编写的 MySqlConnectionHandler 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace WS_Studio_tool
{
class MySqlConnectionHandler
{
private MySqlConnection connection;
private string ConnectionString;
public MySqlConnectionHandler()
{
try
{
ConnectionString = "SERVER=localhost;" +
"DATABASE=ws_creator_beta;" +
"UID=root;" +
"PASSWORD=AF362GL!";
connection = new MySqlConnection(ConnectionString);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "MySql Fehler!");
}
}
public bool InsertRow(string SQL_Query)
{
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = SQL_Query;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "MySql Fehler!");
}
return true;
}
}
}
我的函数调用(我经常使用它,因此它可能包含不必要的东西):
string newquery = QueryTextBox1.ToString();
MySqlConnectionHandler SqlHandler = new MySqlConnectionHandler();
SqlHandler.InsertRow(newquery);
还有我的 MySql 查询:
INSERT INTO user_data (username,passwd) VALUES ('asdf', 'asdf');
如果有人可以快速查看一下,那就太好了,也许您能够找到错误..
最佳答案
你不是telling the command to execute :另外,您需要明确 open the connection before using it ,因此将这些行添加到 InsertRow:
connection.Open();
command.ExecuteNonQuery();
我还建议您在完成连接后将其释放 - 通过在 MySqlConnectionHandler
类上实现 IDisposable
,或者 - 更简单 - 只需创建一个执行查询时 using
block 内的连接:
using (var connection = new new MySqlConnection(ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = SQL_Query;
connection.Open();
command.ExecuteNonQuery();
}
}
关于c# - 不执行我的 MySql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313572/