Downloading Connector/Net: Insert Update Select Delete
Downloading Connector/Net: Insert Update Select Delete
Introduction
The purpose of this article is to show in a step by step manner how to use and connect C# with
MySql using MySql Connect/NET. I will create simple examples about the DML
(Insert, Update, Select, Delete) 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.
Now let's create the database, and the table that we are going to query from our application
later on.
And we create the table that we will query from our application:
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:
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.
//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 + ";";
//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()
{
}
}
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.
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;
}
}
Usually, Insert, update 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 Insert, update and delete, which are the easiest. The process to successfully
execute a command is as follows:
//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();
}
}
//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();
//close Connection
this.CloseConnection();
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:
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}
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:
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:
Now back to our application, to backup the database, we will have to set
the RedirectStandardOutput to true, and read the output from the process into
a string and save it to a file.
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.
Conclusion
In this article, I demonstrated how to connect C# to MySQL and query the tables using simple
examples for the insert, update, delete 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 fro