C#/MySql 3: Create database
Written by: maffelu , 2009-04-17 07:27:51
MySqlConnection connect;
string connectionLine;
//Create a connection string
connectionLine = "Data source=localhost;UserId=root;Password=dog;";
//Instantiate the MySqlConnection class, constructor takes one connectionstring
connect = new MySqlConnection(connectionLine);
//Instantiate the MySqlCommand class
cmd = new MySqlCommand();
try
{
//Create a connection
cmd.Connection = connect;
//Open the connection
cmd.Connection.Open();
Console.WriteLine("Connection opened.");
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
//Create a query
commandLine = "CREATE DATABASE mydb;";
//Set the command query
cmd.CommandText = commandLine;
//Execute the command query
cmd.ExecuteNonQuery();
using System;
using MySql.Data.MySqlClient;
namespace MorkConsTest
{
class Program
{
static void Main(string[] args)
{
MySqlConnection connect;
MySqlCommand cmd;
string connectionLine;
string commandLine;
//Create a connection string
connectionLine = "Data source=localhost;UserId=root;Password=dog;";
//Instantiate the MySqlConnection class, constructor takes one connectionstring
connect = new MySqlConnection(connectionLine);
//Instantiate the MySqlCommand class
cmd = new MySqlCommand();
try
{
//Create a connection
cmd.Connection = connect;
//Open the connection
cmd.Connection.Open();
Console.WriteLine("Connection opened.");
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
//Create a query
commandLine = "CREATE DATABASE mydb;";
//Set the command query
cmd.CommandText = commandLine;
try
{
//Execute the command query
cmd.ExecuteNonQuery();
Console.WriteLine("Database created.");
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
//Close the connection
cmd.Connection.Close();
Console.WriteLine("Connection closed.");
}
Console.Read();
}
}
}
There are no comments on this article.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only
Maffelu
Creator and admin of MorkaLork.com.
Started programming in HTML back when frames and tables was the way to design a page, moved on to Pascal/Delphi, PHP, javascript/jQuery, VB.NET/C#, Java and C++.
Currently studies .NET (in general) focusing on ASP.NET.