Connect C# to MySQL using MySQL Connector/Net, Insert, Update, Select, Delete example, Backup and restore MySQL database from C# or .NET application

Introduction

The purpose of this article is to show in a step by step manner how to use and connect C# with MySql usingMySql Connect/NET. I will create simple examples about the DML (InsertUpdateSelectDelete) throughout the article to show how to query the database using C#, and in the end I will show you how to backup your database and save it in a .sql file from our application, and how to restore it back.

Getting Started

Downloading Connector/Net

First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.

Creating the Database

Now let's create the database, and the table that we are going to query from our application later on.

From the command line, we start by creating the database:

Hide   Copy Code
create database ConnectCsharpToMysql;

Then we select the database to use before creating the table:

Hide   Copy Code
use ConnectCsharpToMysql;

And we create the table that we will query from our application:

Hide   Copy Code
create table tableInfo
(
id INT NOT NULL AUTO INCREMENT,
name VARCHAR(30),
age INT,
PRIMARY KEY(id)
);

Using the Code

Adding Reference and Creating the MySQL Connector DLL from the Project

Before we start writing the code, we need to add the mysql Reference in our project. To do so, we right click our project name, and choose Add Reference:

Then we choose MySql.Data from the list:

In order to use the application on other computers that don't have the connector installed, we will have to create a DLL from the reference. To do so, we right click the reference name in our project, and set the copy local to truein its properties:

Creating the Class

It's always a better idea to create a new class for connecting to the database and to separate the actual code from the code that will access the database. This will help keep our code neat, easier to read and more efficient.

We will start by adding the MySql Connector library:

Hide   Copy Code
//Add MySql Library
using MySql.Data.MySqlClient;

Then declaring and initializing the variables that we will use:

  • connection: will be used to open a connection to the database.
  • server: indicates where our server is hosted, in our case, it's localhost.
  • database: is the name of the database we will use, in our case it's the database we already created earlier which is connectcsharptomysql.
  • uid: is our MySQL username.
  • password: is our MySQL password.
  • connectionString: contains the connection string to connect to the database, and will be assigned to the connection variable.

Our class will look as follows: 
(Empty methods will be filled later on in this article.)

Hide   Shrink    Copy Code
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()
{
}
}

Opening and Closing the Connection

We should always open a connection before querying our table(s), and close it right after we're done, to release the resources and indicate that this connection is no longer needed. 
Opening and closing a connection to the database is very simple, however, it's always better to use exception handling before opening a connection or closing it, to catch the errors and deal with them.

Hide   Shrink    Copy Code
//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;
}
}

Working with DML (Insert, Update, Select, Delete)

Usually, Insertupdate and delete are used to write or change data in the database, while Select is used to read data. 
For this reason, we have different types of methods to execute those queries. 
The methods are the following:

  • ExecuteNonQuery: Used to execute a command that will not return any data, for example Insert,update or delete.
  • ExecuteReader: Used to execute a command that will return 0 or more records, for example Select.
  • ExecuteScalar: Used to execute a command that will return only 1 value, for example Select Count(*).

I will start with Insertupdate and delete, which are the easiest. The process to successfully execute a command is as follows:

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using theConnection and the CommandText methods in the MySqlCommand class.
  4. Execute the command.
  5. Close the connection.
Hide   Shrink    Copy Code
//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();
}
}

To execute a Select statement, we add a few more steps, and we use the ExecuteReader method that will return a dataReader object to read and store the data or records.

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using theConnection and the CommandText methods in the MySqlCommand class.
  4. Create a MySqlDataReader object to read the selected records/data.
  5. Execute the command.
  6. Read the records and display them or store them in a list.
  7. Close the data reader.
  8. Close the connection.
Hide   Shrink    Copy Code
//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;
}
}

Sometimes, a command will always return only one value, like for example if we want to count the number of records, we have been using Select Count(*) from tableinfo;, in this case, we will have to use the method ExecuteScalar that will return one value.

The process to successfully run and ExecuteScalar is as follows:

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using theConnection and the CommandText methods in the MySqlCommand class.
  4. Execute the command.
  5. Parse the result if necessary.
  6. Close the connection.
Hide   Copy Code
//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;
}
}

Backup and Restore the Database

Before I show you how to backup the database from our application, I will explain a little bit about processes, commands, arguments and the input and output. 
Usually, to backup a MySQL database from the command line, we write the following:

Hide   Copy Code
mysqldump -u username -p password -h localhost ConnectCsharpToMysql > "C:\Backup.sql"

and to restore it, we write:

Hide   Copy Code
mysql -u username -p password -h localhost ConnectCsharpToMysql < "C:\Backup.sql"

The following commands can be divided as such:

  • mysql and mysqldump are the filename or the executable file.
  • -u username -p password -h localhost are the arguments.
  • > "C:\Backup.sql" is where the output is directed.
  • < "C:\Backup.sql" is where the input is directed.

Now that we know how the command is divided, we can start implementing it in our application.

In C# and .NET applications, starting a process is easy. First we add the library:

Hide   Copy Code
using System.Diagnostics;

Then we launch an application, such as Internet Explorer:

Hide   Copy Code
Process.Start("IExplore.exe");

ProcessStartInfo is used in conjunction with Process, to setup the process before it starts. 
For example, to start Internet Explorer with arguments, we write the following:

Hide   Copy Code
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "IExplore.exe";
psi.Arguments = "www.codeproject.com";
Process.Start(psi);

To write our output to a file or read our input, we can use the RedirectStandardInput andRedirectStandardOutput properties in the ProcessStartInfo component to cause the process to get input from or return output to a file or other device. If we use the StandardInput or StandardOutputproperties on the Process component, we must first set the corresponding value on the ProcessStartInfoproperty. Otherwise, the system throws an exception when we read or write to the stream.

Now back to our application, to backup the database, we will have to set the RedirectStandardOutput totrue, and read the output from the process into a string and save it to a file.

Hide   Shrink    Copy Code
//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!");
}
}

To restore the database, we read the .sql file and store it in a string, then set the RedirectStandardInputproperty to true, and write the input from the string to the process.

Hide   Shrink    Copy Code
//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!");
}
}

Conclusion

In this article, I demonstrated how to connect C# to MySQL and query the tables using simple examples for theinsertupdatedelete and select statements. 
Also, and because it's not widely available over the internet, I decided to demonstrate how to backup and restore a MySQL database from the C# application.

Connect C# to MySQL的更多相关文章

  1. mySql 远程连接(is not allowed to connect to this MySQL server)

    如果你想连接你的mysql的时候发生这个错误: ERROR 1130: Host '192.168.1.3' is not allowed to connect to this MySQL serve ...

  2. 报错:1130-host ... is not allowed to connect to this MySql server

    报错:1130-host ... is not allowed to connect to this MySql server   解决方法: 1. 改表法. 可能是你的帐号不允许从远程登陆,只能在l ...

  3. 连接Mysql提示Can’t connect to local MySQL server through socket的解决方法

    mysql,mysqldump,Mysqladmin,php连接mysql服务常会提示下面错误: ERROR 2002 (HY000): Can't connect to local MySQL se ...

  4. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    有时候,当我们使用"mysql"."mysqladmin"."mysqldump"等命令管理数据库时,服务器抛出类似如下错误: 一.错误现场 ...

  5. MySql数据库:Host 'localhost' is not allowed to connect to this MySQL server

    修改mysql的root密码后,出现Host 'localhost' is not allowed to connect to this MySQL server 错误. 解决办法: C:\Progr ...

  6. XtraBackup出现 Can't connect to local MySQL server through socket '/tmp/mysql.sock'

    Xtrabackup做备份时遇到下面错误信息MySQL server: Can't connect to local MySQL server through socket '/tmp/mysql.s ...

  7. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    从供应商手中接手一个云平台(Windwos Azure)上的MySQL数据库,登录数据库时遇到错误: $mysql -uroot -p Enter password: ERROR 2002 (HY00 ...

  8. ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了(转载)

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var mysql 启动不了   ps -A | gr ...

  9. Mac mySql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)的解决办法

    我的环境:Mac 10.11.6 ,mysql  5.7.14  . mac mySql 报错ERROR 2002 (HY000): Can't connect to local MySQL serv ...

  10. 启动Mysql服务提示Can’t connect to local MySQL server through socket的解决方法

    启动Mysql服务常会提示下面错误: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/ ...

随机推荐

  1. BZOJ3697:采药人的路径(点分治)

    Description 采药人的药田是一个树状结构,每条路径上都种植着同种药材. 采药人以自己对药材独到的见解,对每种药材进行了分类.大致分为两类,一种是阴性的,一种是阳性的. 采药人每天都要进行采药 ...

  2. BZOJ1468:Tree(点分治)

    Description 给你一棵TREE,以及这棵树上边的距离.问有多少对点它们两者间的距离小于等于K Input N(n<=40000) 接下来n-1行边描述管道,按照题目中写的输入 接下来是 ...

  3. 9、Dubbo-配置(4)

    本地存根 远程服务后,客户端通常只剩下接口,而实现全在服务器端,但提供方有些时候想在客户端 也执行部分逻辑,比如:做 ThreadLocal 缓存,提前验证参数,调用失败后伪造容错数据等 等,此时就需 ...

  4. centos上nginx的安装

    安装步骤:   1.下载nginx,执行:wget http://nginx.org/download/nginx-1.10.2.tar.gz 2.解压,执行:tar vxzf nginx-1.10. ...

  5. leaflet 中文API

    LeafLet js 官网:http://leafletjs.com/index.html LeafLet js 官网demo: http://leafletjs.com/examples.html ...

  6. xmppframework 简介

    XMPPFramework是一个OS X/iOS平台的开源项目,使用Objective-C实现了XMPP协议(RFC-3920),同时还提供了用于读写XML的工具,大大简化了基于XMPP的通信应用的开 ...

  7. VPP(Vector Packet Processing)浅析

    VPP简介 VPP(Vector Packet Processing)是思科旗下的一款可拓展的开源框架,提供容易使用的.高质量的交换.路由功能 特点:高性能.运行在普通的cpu上. 优点:高性能.技术 ...

  8. Python 学习笔记(十三)Python函数(二)

    参数和变量 >>> def foo(a,b): #函数是一个对象 return a+b >>> p =foo #对象赋值语句.将foo函数赋值给p这个变量 > ...

  9. 删除 center os7 openjdk

    卸载CentOS7-x64自带的OpenJDK并安装Sun的JDK7的方法   第一步:查看并卸载CentOS自带的OpenJDK 安装好的CentOS会自带OpenJdk,用命令 java -ver ...

  10. vue项目获取当前地址栏参数(非路由传参)

    项目中遇到一个需求,就是另一个管理系统带参直接单纯的跳转跳转到vue pc项目中的某个页面,后再初始化查询数据,参数以地址栏的形式传入 管理系统:打开新地址地址 let obj = { id: 21, ...