c# - C#连接Mysql数据库

标签 c# mysql database-connection

我想从 C# 连接到 mysql 服务器。我在网上找到了一些代码,但某处有问题,因为我得到了

A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll

错误。

private void Initialise()
    {
        server = "dns to server";
        database = "db_name";
        uid = "root";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
                            database + ";" + "UID=" +
                            uid + ";" + "PASSWORD=" + password + ";";
          OR
        connectionString = "Server=xxx.no-ip.org;Database=rdb;"+
                "Uid=root;Pwd=wHt2%Zt;";
        connection = new MySqlConnection(connectionString);
        if (this.OpenConnection() == true)
            Console.Out.Write("SUCCESS");
        else
            Console.Out.Write("ERROR");
    }

private bool OpenConnection()  {
            try   {
                connection.Open();
                return true;
            }
            catch (MySqlException ex){                    
                switch (ex.Number) {
                    case 0:
                        MessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;    
                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }

我在控制台上没有收到任何消息。我添加了 Mysql.Data 作为对我的项目的引用,并且我使用了 using MySql.Data.MySqlClient;

我也尝试通过 gui 连接,但没有成功。想法?

编辑 1:使用任一连接字符串我的程序仍然无法运行。

编辑 2:添加了 OpenConnection 方法。

编辑 3:This is the error i get !

最佳答案

附:

http://www.connectionstrings.com/mysql

可能您需要改变您的方法...使用 webconfig 或应用程序配置来设置并从配置中读取您的连接字符串...

我还建议您阅读此...

http://www.codeproject.com/Articles/12300/An-ASP-NET-Application-Using-a-MySQL-Database

更新

根据您更新的发现...可能有两个问题,首先仔细检查您的连接字符串,其次是检查用户“root”是否具有所需的权限。

关于c# - C#连接Mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12185296/

相关文章:

php - 从 CodeIgniter 中的数据库获取下拉列表

php - where 子句中的列 'id' 对于 3 个表不明确 Codeigniter

java - 错误 java.net.socketException : permission denied mysql android

c# - 请求用@variable替换列名

c# - 你如何制作一个非模态最顶层对话框,该对话框仅相对于 WinForms 中的父窗体最顶层?

c# - 在 ASP.NET Core MVC 中将表单发布到 Controller 不起作用

mysql - 我可以告诉Mysql哪些索引保留在内存中而不管其他索引吗?

c# - 当许多文件同时添加到目录时,FileSystemWatcher 无法正常工作

python - 导入错误 : No localization support for language 'eng' in python

c# - 设置连接设置的最佳方法