Click here to Skip to main content
15,884,793 members
Articles / Database Development / MySQL

Using MySQL from C# and Mono.NET

Rate me:
Please Sign up or sign in to vote.
4.74/5 (13 votes)
3 Jul 20054 min read 180.1K   2.7K   60  
An article on connecting to and using MySQL from Mono.
using System;
using System.Configuration;
using ByteFX.Data;
using System.IO;
using System.Reflection;

public class MySQLConsole
{
	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
		{
			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();

				//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));
				}

			}

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

	}
	
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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


Written By
Software Developer (Senior)
United Kingdom United Kingdom
Sixteen years experience in software programming and web development, using C, Visual Basic and C Sharp on Windows and Linux.

Comments and Discussions