MySQL CSharp Tutorial
MySQL CSharp Tutorial
http://zetcode.com/db/mysqlcsharptutorial/
About this tutorial
This is a C# tutorial for the MySQL database. It covers the basics of MySQL programming
with C#. In this tutorial, we use the Connector/Net driver. This driver is based on the
ADO.NET specification. The examples were created and tested on Ubuntu Linux. There is
a similar MySQL Visual Basic tutorial on ZetCode.
If you need to refresh your knowledge of the C# language, there is a full C# tutorial on
ZetCode.
Before we start
On Linux, we need to install several packages to execute the examples in this tutorial:
libmysql6.1-cil, mysql-server, mysql-client. We also need to install C# compiler
from the Mono project, either from a package or from sources.
The libmysql6.1-cil is the MySQL database connector for CLI. It is written in C# and is
available for all CLI languages: C#, Visual Basic, Boo, and others.
$ ls /usr/lib/cli/MySql.Data-6.1/MySql.Data.dll
/usr/lib/cli/MySql.Data-6.1/MySql.Data.dll
From the technical point of view, we need a DLL. On an Ubuntu Linux, it was located
under the above path. We need to know the path to the DLL library. To compile our
examples.
We check if the MySQL server is running. If not, we need to start the server.
$ sudo -b /usr/local/mysql/bin/mysqld_safe
The above command starts MySQL server using the MySQL server startup script. The way
how we start a MySQL server might be different. It depends whether we have installed
MySQL from sources or from packages and also on the Linux distro. For further
information consult MySQL first steps or your Linux distro information.
Next, we are going to create a new database user and a new database. We use the mysql
client.
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 30
Server version: 5.0.67-0ubuntu6 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
We use the mysql monitor client application to connect to the server. We connect to the
database using the root account. We show all available databases with the SHOW DATABASES
statement.
We create a new mydb database. We will use this database throughout the tutorial.
mysql> quit;
Bye
We create a new database user. We grant all privileges to this user for all tables of the mydb
database.
Definitions
ADO.NET is an important part of the .NET framework. It is a specification that unifies
access to relational databases, XML files and other application data. A MySQL
Connector/Net is an implementation of the ADO.NET specification for the MySQL
database. It is a driver written in C# language and is available for all .NET languages.
The Connection, Command, DataReader, DataSet, and DataProvider are the core
elements of the .NET data provider model. The Connection creates a connection to a
specific data source. The Command object executes an SQL statement against a data source.
The DataReader reads streams of data from a data source. The DataSet object is used for
offline work with a mass of data. It is a disconnected data representation that can hold data
from a variety of different sources. Both DataReader and DataSet are used to work with
data; they are used under different circumstances. If we only need to read the results of a
query, the DataReader is the better choice. If we need more extensive processing of data,
or we want to bind a Winforms control to a database table, the DataSet is preferred.
MySQL version
If the following program runs OK, then we have everything installed OK. We check the
version of the MySQL server.
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
We connect to the database and get some info about the MySQL server.
using MySql.Data.MySqlClient;
string cs = @"server=localhost;userid=user12;
password=34klq*;database=mydb";
This is the connection string. It is used by the data provider to establish a connection to the
database. We specify the host name, user name, password and a database name.
conn.Open();
Here we print the version of MySQL using the ServerVersion property of the connection
object.
} finally
{
if (conn != null)
{
conn.Close();
}
}
$ ./version.exe
MySQL version : 5.5.9
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
We check for the version of the MySQL database. This time using an SQL query.
This is the SQL SELECT statement. It returns the version of the database. The VERSION()
is a built-in MySQL function.
The MySqlCommand is an object, which is used to execute a query on the database. The
parameters are the SQL statement and the connection object.
There are queries which return only a scalar value. In our case, we want a simple string
specifying the version of the database. The ExecuteScalar() is used in such situations.
We avoid the overhead of using more complex objects.
$ ./version2.exe
MySQL version : 5.5.9
We have a books.sql file. It creates two database tables: Authors and Books. The tables
are of InnoDB type. InnoDB databases support foreign key constraints and transactions. We
place a foreign key constraint on the AuthorId column of the Books table. We fill the
tables with initial data.
Prepared statements
Now we will concern ourselves with prepared statements. When we write prepared
statements, we use placeholders instead of directly writing the values into the statements.
Prepared statements increase security and performance.
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
} finally
{
if (conn != null) {
conn.Close();
}
}
}
}
cmd.ExecuteNonQuery();
$ ./prepared.exe
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
while (rdr.Read())
{
Console.WriteLine(rdr.GetInt32(0) + ": "
+ rdr.GetString(1));
}
} finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
}
}
We get all authors from the Authors table and print them to the console.
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ": "
+ reader.GetString(1));
}
The Read() method advances the data reader to the next record. It returns true if there are
more rows; otherwise false. We can retrieve the value using the array index notation, or use
a specific method to access column values in their native data types. The latter is more
efficient.
if (rdr != null)
{
rdr.Close();
}
Always call the Close() method of the reader when done reading.
$ ./retrieve.exe
1: Jack London
2: Honore de Balzac
3: Lion Feuchtwanger
4: Emile Zola
5: Truman Capote
6: Trygve Gulbranssen
Column headers
Next we will show, how to print column headers with the data from the database table.
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
while (rdr.Read())
{
Console.WriteLine(rdr.GetString(0).PadRight(18) +
rdr.GetString(1));
}
} finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
}
}
In this program, we select authors from the Authors table and their books from the Books
table.
This is the SQL statement which joins authors with their books.
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0).PadRight(18) +
reader.GetString(1));
}
We print the data that was returned by the SQL statement to the terminal.
$ ./headers.exe
Name Title
Jack London Call of the Wild
Jack London Martin Eden
Honore de Balzac Old Goriot
Honore de Balzac Cousin Bette
Lion Feuchtwanger Jew Suess
Emile Zola Nana
Emile Zola The Belly of Paris
Truman Capote In Cold blood
Truman Capote Breakfast at Tiffany
using System;
using System.Data;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
string stm = "SELECT * FROM Authors";
MySqlDataAdapter da = new MySqlDataAdapter(stm, conn);
da.Fill(ds, "Authors");
DataTable dt = ds.Tables["Authors"];
dt.WriteXml("authors.xml");
Console.WriteLine("".PadLeft(20, '='));
}
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
We print the authors from the Authors table. We also save them in an XML file. This time,
we use the MySqlDataAdapter and DataSet objects.
da.Fill(ds, "Authors");
DataTable dt = ds.Tables["Authors"];
We get the table called "Authors". We have given a DataSet only one table, but it can
contain multiple tables.
dt.WriteXml("authors.xml");
Console.WriteLine("".PadLeft(20, '='));
}
We display the contents of the Authors table to the terminal. To traverse the data, we utilize
the rows and columns of the DataTable object.
In the next example, we are going to bind a table to a Winforms DataGrid control.
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using MySql.Data.MySqlClient;
public MForm()
{
this.Text = "DataGrid";
this.Size = new Size(350, 300);
this.InitUI();
this.InitData();
this.CenterToScreen();
}
void InitUI()
{
dg = new DataGrid();
dg.CaptionBackColor = System.Drawing.Color.White;
dg.CaptionForeColor = System.Drawing.Color.Black;
dg.CaptionText = "Authors";
void InitData()
{
string cs = @"server=localhost;userid=user12;
password=34klq*;database=mydb";
try
{
conn = new MySqlConnection(cs);
conn.Open();
ds = new DataSet();
da = new MySqlDataAdapter(stm, conn);
da.Fill(ds, "Authors");
dg.DataSource = ds.Tables["Authors"];
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
class MApplication
{
public static void Main()
{
Application.Run(new MForm());
}
}
using System.Windows.Forms;
using System.Drawing;
this.InitUI();
this.InitData();
Inside the InitUI() method, we build the user interface. In the InitData() method, we
connect to the database, retrieve the data into the DataSet and bind it to the DataGrid
control.
dg = new DataGrid();
We will display the data from the Authors table in the DataGrid control.
dg.DataSource = ds.Tables["Authors"];
We bind the DataSource property of the DataGrid control to the chosen table.
$ dmcs -r:/usr/lib/cli/MySql.Data-6.1/MySql.Data.dll -
r:System.Windows.Forms.dll
-r:System.Drawing.dll -r:System.Data.dll dataadapter2.cs
To compile the example, we must include additional DLLs: the DLL for MySQL
connector, for the Winforms, Drawing, and for the Data.
Figure: DataGrid
Transaction support
A transaction is an atomic unit of database operations against the data in one or more
databases. The effects of all the SQL statements in a transaction can be either all committed
to the database or all rolled back.
The MySQL database has different types of storage engines. The most common are the
MyISAM and the InnoDB engines. There is a trade-off between data security and database
speed. The MyISAM tables are faster to process and they do not support transactions. On
the other hand, the InnoDB tables are more safe against the data loss. They support
transactions. They are slower to process.
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
tr = conn.BeginTransaction();
tr.Commit();
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
In this program, we want to change the name of the author on the first row of the Authors
table. We must also change the books associated with this author. A good example where a
transaction is necessary. If we change the author and do not change the author's books, the
data is corrupted.
MySqlTransaction tr = null;
tr = conn.BeginTransaction();
We begin a transaction.
The third SQL statement has an error. There is no 'Titl' column in the table.
tr.Commit();
try
{
tr.Rollback();
In case of an exception, the transaction is rolled back. No changes are committed to the
database. During the rollback there could be an Exception. We handle this in a separate
try/catch statement.
$ ./transaction.exe
Error: MySql.Data.MySqlClient.MySqlException: Unknown column 'Titl' in
'field list'
at MySql.Data.MySqlClient.MySqlStream.ReadPacket () [0x00000]
at MySql.Data.MySqlClient.NativeDriver.ReadResult () [0x00000]
An exception was thrown. The transaction was rolled back and no changes took place.
using System;
using MySql.Data.MySqlClient;
try
{
conn = new MySqlConnection(cs);
conn.Open();
} finally {
if (conn != null)
{
conn.Close();
}
}
}
}
We have the same example. This time, without the transaction support.
$ ./notransaction.exe
Error: MySql.Data.MySqlClient.MySqlException: Unknown column 'Titl' in
'field list'
at MySql.Data.MySqlClient.MySqlStream.ReadPacket () [0x00000]
at MySql.Data.MySqlClient.NativeDriver.ReadResult () [0x00000]
An exception is thrown again. Leo Tolstoy did not write Martin Eden. The data is
corrupted.
Tweet
This was the MySQL C# tutorial, with MySQL Connector. You might be also interested in
MySQL C API tutorial, MySQL Python tutorial or MySQL PHP tutorial.
http://zetcode.com/lang/csharp/
http://zetcode.com/db/mysqlvb/
http://www.ajpdsoft.com/modules.php?name=News&file=article&sid=629
CSharp: Desarrollar aplicación C# con acceso nativo a MySQL Server mediante
ADO.NET
Explicamos en este tutorial cómo desarrollar una aplicación con el lenguaje de programación
Microsoft Visual C# .Net (de la suite de desarrollo Microsoft Visual Studio .Net 2010).
Explicamos cómo realizar una conexión nativa (sin utilizar intermediarios como ODBC ni
OLE DB) a un servidor de bases de datos MySQL Server (sea en Linux o en Windows)
desde nuestra aplicación Microsoft Visual C# .Net mediante ADO.NET (MySQL
Connector Net).
Requisitos para desarrollar aplicación con acceso a MySQL nativo usando Visual C# .Net y
driver Connector/Net ADO.NET.
Desarrollar aplicación C# para acceso a MySQL Server de forma nativa con ADO.NET Driver
for MySQL (Connector/NET).
AjpdSoft Acceso MySQL con ADO.NET en C# en funcionamiento.
Artículos relacionados.
Créditos.
Suite de desarrollo Microsoft Visual Studio .Net 2010: en el siguiente tutorial explicamos
cómo instalar este entorno de desarrollo de aplicaciones .Net:
Instalar Microsoft Visual Studio .Net 2010 y desarrollar aplicación con acceso a
PostgreSQL.
http://dev.mysql.com/downloads/connector/net
En nuestro caso descargaremos la versión 6.6.4 y la plataforma (Select Platform)
"Microsoft Windows", descargaremos "Windows (x86, 32-bit), MSI Installer"
(mysql-connector-net-6.6.4.msi):
Servidor con MySQL Server: necesitaremos, obviamente, un equipo con el motor de base
de datos MySQL instalado y funcionando. En los siguientes enlaces mostramos algunos
ejemplos sobre cómo montar un servidor de MySQL Server en varios sistemas operativos:
La descarga gratuita del código fuente completo: AjpdSoft Acceso MySQL con ADO.NET
en C#.
Añadiremos en el código la cláusula:
using MySql.Data.MySqlClient;
El código C# completo de la aplicación (para los botones de conectar con servidor, usar
esquema, añadir select SQL y ejecutar consulta SQL, así como las funciones para obtener
las bases de datos de MySQL y las tablas de la base de datos seleccionada se muestra a
continuación:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace AjpdSoftAccesoMySQLCsharp
{
public partial class formAccesoMySQL : Form
{
private MySqlConnection conexionBD;
try
{
conexionBD.ChangeDatabase(bd);
public formAccesoMySQL()
{
InitializeComponent();
}
string connStr =
String.Format("server={0};port={1};user id={2};
password={3}; " +
"database=mysql; pooling=false;" +
"Allow Zero Datetime=False;Convert Zero Datetime=True",
txtServidor.Text,txtPuerto.Text, txtUsuario.Text,
txtContrasena.Text);
try
{
conexionBD = new MySqlConnection(connStr);
conexionBD.Open();
obtenerBasesDatosMySQL();
}
catch (MySqlException ex)
{
MessageBox.Show("Error al conectar al servidor de MySQL:
" +
ex.Message, "Error al conectar",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
try
{
tabla = new DataTable();
dbGrid.DataSource = tabla;
}
catch (Exception ex)
{
MessageBox.Show("Error al mostrar los datos de la
tabla [" +
lsTablas.Text + "] de MySQL: " +
ex.Message, "Error ejecutar SQL",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (opNoDatos.Checked)
{
try
{
int numeroRegistrosAfectados = 0;
Tras introducir los datos de conexión pulsaremos en el botón "1 Conectar con servidor", si
los datos son correctos y el servidor está disponible, la aplicación obtendrá los catálogos
(bases de datos) del servidor de MySQL Server (a los que el usuario tenga permisos):
Seleccionaremos la tabla que usaremos para la consulta SQL y pulsaremos "3 Select (SQL)
de la tabla":
Para este tipo de consultas SQL la aplicación devolverá el número de registros afectados:
Artículos relacionados
AjpdSoft Acceso MySQL con ADO.NET en C#.
Capturar pantalla screenshot con Visual C#.
Separar páginas pdf en un pdf por cada página con PDFsharp y Visual C# C Sharp.
Extraer texto y metadatos de fichero PDF con Visual C# .Net y iTextSharp.
Instalar Microsoft Visual Studio .Net 2010 y desarrollar aplicación con acceso a
PostgreSQL.
Convertir texto a PDF con iTextSharp y Visual Basic .Net VB.Net.
Generar y leer códigos QR Quick Response Barcode con Visual Basic .Net VB.Net.
Cómo desarrollar una aplicación de servicio en Windows con Visual Basic .Net.
Estructura del código de barras EAN 13 y ejemplo en Delphi de obtención de datos.
AjpdSoft Generador de códigos de barras.
AjpdSoft extraer texto PDF Delphi.
AjpdSoft Convertir Texto a PDF VB.Net.
AjpdSoft Indexar Texto PDF C# iTextSharp.
AjpdSoft Separar Páginas PDF código fuente Visual C# .Net.
AjpdSoft Socket VB.Net.
AjpdSoft Envío SMS VB.Net.
AjpdSoft Inventario PCs - Código fuente Delphi.
AjpdSoft Insertar Evento Google Calendar VB.net.
AjpdSoft Envío EMail SSL VB.Net.
AjpdSoft Conexión BD Visual Basic .Net.
Desarrollar aplicación lector de códigos de barras para Android con App Inventor.
Metadatos, cómo eliminarlos, cómo consultarlos, peligrosos para la privacidad.
Insertar evento de Google Calendar con Visual Basic .Net y Google Data API.
Crear proceso en segundo plano con barra de progreso en Visual Basic .Net VB.Net.
Instalar Visual Studio 2010 y desarrollar aplicación con acceso a PostgreSQL.
El control de errores en Visual Basic .Net.
Acceso a MySQL mediante Visual Basic .Net y ODBC.
Acceso a Oracle mediante Microsoft Visual Basic, RDO y ODBC.
Insertar y extraer documentos en una tabla Oracle con Visual Basic 6.
Cambiar marcadores de Word por valores del formulario de una aplicación.
Exportar ListView a fichero CSV VB.Net.
Función para reemplazar una cadena de texto dentro de otra - Visual Basic.
Funciones para leer y escribir en ficheros INI VB.Net.
Artículos, manuales y trucos del Proyecto AjpdSoft sobre Microsoft Visual Studio.
Todos los programas con código fuente en Visual Basic.
Foro del Proyecto AjpdSoft sobre Visual Basic, Visual C# C Sharp, VB.Net.
Cómo instalar MySQL Server en Windows XP.
Cómo instalar MySQL Server 6.0 Alpha en Windows XP.
Instalar y configurar MySQL Server 5 en Linux Suse 10.
Cómo instalar MySQL Server en Linux y permitir conexiones remotas.
Instalar y configurar MySQL Server 5 en Linux Suse 10.
Manual SQL con ejemplos de sentencias SQL Oracle.
Exportar una tabla Microsoft Access a MySQL.
Cómo cargar un fichero de texto plano en una tabla MySQL.
Definición IDE.
Definición URL.
Definición SQL.
Definición OLE DB.
Definición ODBC.
Créditos
Artículo realizado íntegramente por Alonsojpd miembro fundador del Proyecto AjpdSoft.