5,543,170 members and growing! (160 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » Cross Platform » Mono     Intermediate

Using MySQL from C# and Mono.NET

By Custec

An article on connecting to and using MySQL from Mono.
C#, XML, SQL, Windows, .NET 1.1, .NET, MySQL, ADO.NET, Visual Studio, VS.NET2003, DBA, Dev

Posted: 3 Jul 2005
Updated: 3 Jul 2005
Views: 72,624
Bookmarked: 36 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
12 votes for this Article.
Popularity: 5.11 Rating: 4.73 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 16.7%
4
10 votes, 83.3%
5

Windows XP Version

Introduction

Most programs need some kind of database connectivity. It may be for storing data, settings or license details. If you are used to using Visual Studio .NET in Windows, you will usually use ADO.NET to connect to Access or SQL Server, so what do you use in Linux. The most commonly used database on this platform is MySQL which is also available for Windows. If you want to produce a truly cross platform application, MySQL is the preferred choice. In this article, I will demonstrate how you can connect to and create a new database in MySQL from a Console application using Mono. Mono is the open source implementation of the Microsoft .NET Framework, CLR, C# and Visual Basic compilers. In fact the application you produce from this article will run on both platforms without modifications.

Background

The basics of connecting to databases is more or less the same using Mono as in Microsoft .NET. The main difference is the data provider used to connect and run commands. When writing this article, I used the latest version of Mono 1.1.8 installed on SUSE Linux 9.3 Professional. This includes the ByteFX provider for MySQL. If you install the Windows install of Mono 1.1.8, you can follow this article on the Windows platform. You will also need the latest free version of MySQL downloaded from the MySQL website (version 4.1) or from your Linux distros media. In SUSE 9.3, this is included in the installation as well as an administration application and query browser.

This article assumes you have basic SQL skills and know how to log into MySQL from the command line. After you have installed MySQL and Mono, connect to your MySQL server using a console in Linux or the command prompt on Windows. Set the server to use OLD_PASSWORD encryption using the following command at the MySQL prompt.

mysql> SET PASSWORD FOR root@yourserver = OLD_PASSWORD('yourpassword')

Failure to do this will result in a protocol error when connecting from your application. I wrote the application featured in this article using MonoDevelop, the open source free .NET development environment, but you could just as easily use the Kate or Emacs text editors on Linux. On Windows, I recommend SharpDevelop, Visual Studio .NET or Notepad.

Using the code

To keep the code as simple as possible, I used a single C# class file and a configuration file. The configuration file should be placed in the application directory and named as per your exe file with a .config extension, i.e., yourApp.exe.config.

In the configuration file, place the MySQL connection string setting in the following format replacing mypassword with your own connection password.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>l;
    <appSettings>
        <add key="mysqlConnectionString" 
           value="Server=localhost;User ID=root;password=mypassword;" />
    </appSettings>
</configuration>

Of course we could have hard coded this into the application but this is a good coding practice which will allow the server to be changed without recompiling the application.

Create a new file in your choice of editor and save as Main.cs. This will be our application source file. At the very top of this file, we need to import the namespaces we wish to use in the class as follows:

using System;
using System.Configuration;
using ByteFX.Data;
using System.IO;
using System.Reflection;

As in any application, we need an entry point class and Main method, so you can now add this to your class file as below including some variables we will be using in the Main function.

class MainClass
{
    private static string connectionString = string.Empty;
    private static string databaseName = string.Empty;
    private static ByteFX.Data.MySqlClient.MySqlConnection mysqlConn;

    public static void Main(string[] args)
    {
        try
        {

        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
}

In order to connect to your MySQL database, we now need to add code to the Main function to read in the connection string from the configuration file. You could of course extend this code to look at the command args and therefore specify a connection string dynamically in the command line.

public static void Main(string[] args)
{
    try
    {
        connectionString = 
          ConfigurationSettings.AppSettings["mysqlConnectionString"].ToString();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
}

In order to create a database, a database name is required from the user. If a name is input, the database connection is initialized and opened. You can see from the code below that I have also added a finally block to ensure the connection will be closed and marked as disposed before the application exits.

public static void Main(string[] args)
{
    try
    {
        connectionString = 
          ConfigurationSettings.AppSettings["mysqlConnectionString"].ToString();

        Console.WriteLine("Please enter a new database name:");
        databaseName = Console.ReadLine();

        if(databaseName.Length > 0)
        {
            mysqlConn = new ByteFX.Data.MySqlClient.MySqlConnection();
            mysqlConn.ConnectionString = connectionString;
            mysqlConn.Open();
        }

    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
    finally
    {
        if(mysqlConn != null)
        {
            mysqlConn.Close();
            mysqlConn.Dispose();
        }
    }
}

The next code extract shows the creation of the SQL script and the use of a MySqlCommand object to execute it. If successful, the user is informed that the database was created.

...
if(databaseName.Length > 0)
{
    mysqlConn = new ByteFX.Data.MySqlClient.MySqlConnection();
    mysqlConn.ConnectionString = connectionString;
    mysqlConn.Open();

    //Create the sql script...

    string createdbSql = 
      string.Format("CREATE DATABASE {0}", databaseName);

    using(ByteFX.Data.MySqlClient.MySqlCommand cmd
        = new ByteFX.Data.MySqlClient.MySqlCommand(createdbSql, mysqlConn))
    {
        cmd.ExecuteNonQuery();
        Console.WriteLine(string.Format("Database" + 
                " {0} successfully created", databaseName));
    }

}
...

Compiling the code

This article has described how you can connect to and interact with a MySQL Server installation using Mono or Microsoft .NET. To compile this code outside of an IDE, run the following from a command window in the application directory:

mcs Main.cs /r:ByteFX.Data /r:Mono.Posix 
            /r:ICSharpCode.SharpZipLib /out:MySQLConsole.exe

On Windows, run the application using the Microsoft CLR, and on Linux su to root and run the following from a command window in the application directory:

mono MySQLConsole.exe

History

  • Version 1.0 - 28/06/2005.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Custec


Twelve years experience in software programming and web development, using C, Visual Basic and C Sharp on Windows and Linux.

Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular Cross Platform articles:

  • Introduction to Mono - Your first Mono app
    The first in a series of articles about Mono. This article explains how to install Mono and shows how to compile your first Cross Platform application.
  • MONO: an alternative for the .NET framework
    This article presents possibilities for development of .NET applications running on operating systems other than Windows, using the MONO platform. Advantages and challenges will be presented. Also presented are some common issues encountered while developing applications using the .NET technology.
  • Embed ActiveX controls inside Java GUI
    With this your Java projects can take advantage of ActiveX controls and Office documents such as spreadsheets, charts, calendars, word processors, specialized graphics, and many more.
  • Introduction to Mono - ASP.NET with XSP and Apache
    The second article in a series of articles about Mono. This article explains how to host and serve ASP.NET Web Applications and Web Services on Linux using XSP and Apache with the help of Mono.
  • Phalanger, PHP for .NET: Introduction for .NET developers
    Phalanger is a PHP language compiler for the .NET Framework which introduces PHP as a first-class .NET citizen.
Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 13 of 13 (Total in Forum: 13) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralArticle out of datememberYuval Naveh10:52 8 Jul '08  
GeneralRe: Article out of datememberCustec2:51 9 Jul '08  
GeneralRe: Article out of datememberYuval Naveh3:01 9 Jul '08  
QuestionSql server2005 connection errormemberS.S.Sivaprasad22:11 10 Oct '07  
Generaltanx friendmemberJuan Carlos Guillén Zurita10:40 25 Sep '07  
Generalsettings not being retreivedmemberChasingzero14:03 15 Sep '06  
GeneralRe: settings not being retreivedmemberCustec22:58 25 Sep '07  
GeneralClient does not support authentication protocol requested by servermembermsgclb1:00 20 Feb '06  
GeneralRe: Client does not support authentication protocol requested by servermemberCustec22:55 25 Sep '07  
GeneralWhy reference ICSharpCode.SharpZipLib?memberMardawi3:40 13 Jul '05  
GeneralRe: Why reference ICSharpCode.SharpZipLib?memberCustec5:35 13 Jul '05  
GeneralRe: Why reference ICSharpCode.SharpZipLib?memberAlex LE2:10 8 Jan '06  
GeneralMySQL .NET Connector?memberUnruled Boy4:07 4 Jul '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Jul 2005
Editor: Smitha Vijayan
Copyright 2005 by Custec
Everything else Copyright © CodeProject, 1999-2008
Mail5 | Advertise on the Code Project