Connect C# to MySQL






4.90/5 (146投票s)
使用 MySQL Connector/Net 连接 C# 到 MySQL,包含插入、更新、查询、删除示例,以及从 C# 或 .NET 应用程序备份和恢复 MySQL 数据库
入门
下载 Connector/Net
首先,请确保您已从 MySQL 官方网站 下载并安装了 MySQL Connector/NET。本文将使用 Connector/NET 版本 6.1。
创建数据库
现在,让我们创建数据库以及稍后我们将从应用程序查询的表。
在命令行中,我们首先创建数据库
create database ConnectCsharpToMysql;
然后,我们选择要使用的数据库,然后创建表
use ConnectCsharpToMysql;
并创建我们将从应用程序查询的表
create table tableInfo
(
id INT NOT NULL AUTO INCREMENT,
name VARCHAR(30),
age INT,
PRIMARY KEY(id)
);
Using the Code
添加引用并从项目中创建 MySQL Connector DLL
在开始编写代码之前,我们需要在项目中添加 mysql
引用。为此,我们右键单击项目名称,然后选择添加引用:
然后,我们从列表中选择MySql.Data
为了能在没有安装连接器的其他计算机上使用该应用程序,我们必须从引用创建 DLL。为此,我们右键单击项目中的引用名称,并将其复制到本地设置为true
创建类
最好创建一个新类来连接数据库,并将实际代码与访问数据库的代码分开。这将有助于使我们的代码整洁、易于阅读且更高效。
我们将首先添加 MySql Connector 库
//Add MySql Library
using MySql.Data.MySqlClient;
然后声明并初始化我们将使用的变量
connection
:用于打开与数据库的连接。server
:表示我们的服务器托管在哪里,在本例中是 localhost。database
:是我们将在其中使用的数据库的名称,在本例中是我们之前创建的数据库connectcsharptomysql
。uid
:是我们的 MySQL 用户名。password
:是我们的 MySQL 密码。connectionString
:包含连接到数据库的连接字符串,并将分配给 connection 变量。
我们的类将如下所示
(空方法将在本文稍后填充。)
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
}
//Close connection
private bool CloseConnection()
{
}
//Insert statement
public void Insert()
{
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List <string> [] Select()
{
}
//Count statement
public int Count()
{
}
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
打开和关闭连接
在我们查询表之前,应该始终打开连接,并在完成后立即关闭连接,以释放资源并表明此连接不再需要。
打开和关闭数据库连接非常简单,但是,在使用连接或关闭连接之前,最好始终使用异常处理,以捕获错误并进行处理。
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
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;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
处理 DML(插入、更新、选择、删除)
通常,Insert
、update
和 delete
用于写入或更改数据库中的数据,而 Select
用于读取数据。
因此,我们有不同类型的用于执行这些查询的方法。
这些方法如下
ExecuteNonQuery
:用于执行不返回任何数据的命令,例如Insert
、update
或delete
。ExecuteReader
:用于执行返回 0 条或多条记录的命令,例如Select
。ExecuteScalar
:用于执行仅返回 1 个值的命令,例如Select Count(*)
。
我将从最简单的 Insert
、update
和 delete
开始。成功执行命令的步骤如下
- 打开到数据库的连接。
- 创建 MySQL 命令。
- 将连接和查询分配给命令。这可以通过构造函数完成,也可以通过
MySqlCommand
类中的Connection
和CommandText
方法完成。 - 执行命令。
- 关闭连接。
//Insert statement
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete()
{
string query = "DELETE FROM tableinfo WHERE name='John Smith'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
要执行 Select
语句,我们会添加一些额外的步骤,并使用 ExecuteReader
方法,该方法将返回一个 dataReader
对象来读取和存储数据或记录。
- 打开到数据库的连接。
- 创建 MySQL 命令。
- 将连接和查询分配给命令。这可以通过构造函数完成,也可以通过
MySqlCommand
类中的Connection
和CommandText
方法完成。 - 创建一个
MySqlDataReader
对象来读取选定的记录/数据。 - 执行命令。
- 读取记录并显示它们或将它们存储在列表中。
- 关闭数据读取器。
- 关闭连接。
//Select statement
public List< string >[] Select()
{
string query = "SELECT * FROM tableinfo";
//Create a list to store the result
List< string >[] list = new List< string >[3];
list[0] = new List< string >();
list[1] = new List< string >();
list[2] = new List< string >();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
有时,一个命令总是只返回一个值,例如,如果我们想计算记录数,我们一直在使用 Select Count(*) from tableinfo;
,在这种情况下,我们将不得不使用 ExecuteScalar
方法,该方法将返回一个值。
成功运行和 ExecuteScalar
的步骤如下
- 打开到数据库的连接。
- 创建 MySQL 命令。
- 将连接和查询分配给命令。这可以通过构造函数完成,也可以通过
MySqlCommand
类中的Connection
和CommandText
方法完成。 - 执行命令。
- 如果需要,解析结果。
- 关闭连接。
//Count statement
public int Count()
{
string query = "SELECT Count(*) FROM tableinfo";
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}
备份和恢复数据库
在我向您展示如何从我们的应用程序备份数据库之前,我将简要解释一下进程、命令、参数以及输入和输出。
通常,要从命令行备份 MySQL 数据库,我们键入以下内容
mysqldump -u username -p password -h localhost ConnectCsharpToMysql > "C:\Backup.sql"
要恢复它,我们键入
mysql -u username -p password -h localhost ConnectCsharpToMysql < "C:\Backup.sql"
以下命令可分为以下几类
- mysql 和 mysqldump 是文件名或可执行文件。
- -u username -p password -h localhost 是参数。
- > "C:\Backup.sql" 是输出重定向到的位置。
- < "C:\Backup.sql" 是输入重定向到的位置。
现在我们知道了命令是如何划分的,我们可以开始在我们的应用程序中实现它了。
在 C# 和 .NET 应用程序中,启动进程很容易。首先,我们添加库
using System.Diagnostics;
然后,我们启动一个应用程序,例如 Internet Explorer
Process.Start("IExplore.exe");
ProcessStartInfo
与 Process
一起使用,用于在进程启动前对其进行设置。
例如,要带参数启动 Internet Explorer,我们键入以下内容
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "IExplore.exe";
psi.Arguments = "www.codeproject.com";
Process.Start(psi);
要将输出写入文件或读取输入,我们可以使用 ProcessStartInfo
组件中的 RedirectStandardInput
和 RedirectStandardOutput
属性,使进程从文件或其他设备获取输入或向文件或其他设备返回输出。如果我们使用 Process
组件上的 StandardInput
或 StandardOutput
属性,我们必须先在 ProcessStartInfo
属性上设置相应的值。否则,当我们在流上读取或写入时,系统将抛出异常。
现在回到我们的应用程序,要备份数据库,我们将不得不设置 RedirectStandardOutput
为 true
,并将进程的输出读取到一个 string
并保存到文件中。
//Backup
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\MySqlBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}
要恢复数据库,我们读取 .sql 文件并将其存储在 string
中,然后将 RedirectStandardInput
属性设置为 true
,并将 string
中的输入写入进程。
//Restore
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to Restore!");
}
}
结论
在本文中,我通过简单的示例演示了如何将 C# 连接到 MySQL 并使用 insert
、update
、delete
和 select
语句查询表。
此外,由于 MySQL 数据库的备份和恢复在互联网上并非广泛可用,我决定演示如何从 C# 应用程序备份和恢复 MySQL 数据库。
历史
- 2009 年 11 月 17 日:初始发布