简体   繁体   English

如何将 MySQL 数据库连接到 C# WinForm 应用程序?

[英]How to connect MySQL database to C# WinForm Application?

How do you connect a MySQL database to a C# WinForm Application?如何将 MySQL 数据库连接到 C# WinForm 应用程序?

I can establish a connection using a Microsoft SQL Server, but cannot for the life of me figured out how it's done using MySQL.我可以使用 Microsoft SQL Server 建立连接,但我终生无法弄清楚它是如何使用 MySQL 完成的。

You'll need MySQL Connector / Net .您将需要 MySQL Connector / Net 。 Install this, then you'll get a suite of classes like MySqlConnection, MySQLCommand, MySQLDataReader, etc.安装这个,然后你会得到一套类,比如 MySqlConnection、MySQLCommand、MySQLDataReader 等。

These are analogous to SqlConnection and similar classes for MS Sql Server.这些类似于 SqlConnection 和 MS Sql Server 的类似类。

https://dev.mysql.com/downloads/connector/net/6.9.html https://dev.mysql.com/downloads/connector/net/6.9.html

Use this code:使用此代码:

string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";
private void button1_Click(object sender, EventArgs e)
{
    MySqlConnection cnn = new MySqlConnection(myConnectionString);
    try
    {
        cnn.Open();
        MessageBox.Show ("Connection Open!");
        cnn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot open connection!");
    }
}

Make sure that you have a proper reference in your code:确保您的代码中有正确的引用:

using MySql.Data.MySqlClient;

And this connection string is just an example.而这个连接字符串只是一个例子。 You have to see what is your connection string ofc.你必须看看你的连接字符串是什么。 And also search for these kind of questions because I'm sure that there is a bunch of similar or even the same questions on StackOverflow.还要搜索这些问题,因为我确信在 StackOverflow 上有很多类似甚至相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM