c# - 不执行我的 MySql 查询

标签 c# mysql

我的 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/

相关文章:

c# - c#从sql数据库读取数据内存泄漏

c# - 如何使 ASP.NET 网站与 TCP 服务器应用程序通信

c# - 尝试确定托管您的应用程序的 dotnet.exe 的进程 ID 时发生错误。发生一个或多个错误

mysql - 按工作日分组

mysql - Sequelize 在查询中包含多个表

c# - ListView 更改 Metro Apps 中的文本大小

c# - Unity3D第三方C#库包含

mysql - SQL Server Migration Assistant (SSMA) - 它会删除源数据吗?

MySQL 可能进行团队对团队比赛,其中一名玩家可以属于多个团队

mysql - Spring Boot、Spring Security、MySQL - CustomUserDetailsS​​ervice 始终导致错误 "Invalid Username or Password"