2012年12月23日日曜日

Connect to MySql (XAMPP) from .Net by using C#

This note shows how to connect to a database "forcsharp"  created
in MySql (installed alongwith XAMPP) from a C# program in VS2012.

1. Create a project in VS.
In project, add reference, add "MySql.Data" and "MySql.Web".
If there is none of them, you should go to the following link,
download and install MySql Connector for .Net.
http://www.mysql.com/downloads/connector/

2. Create a database called "forcsharp" and a table called "Customer"
in MySql through XAMPP, MySql Admin.

3. Add using MySql.Data.MySqlClient.
Connect to database use connection string.
Server=myserver;Database=mydatabase;Uid=myuserid;Pwd=mypassword;"
using System;
using System.Data;
using MySql.Data.MySqlClient;
 
namespace XMLDemo2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // Connect by connection string.
            const string myConnectionString = "Server=localhost;Database=forcsharp;Uid=root;Pwd=";
            var connection = new MySqlConnection(myConnectionString);
            connection.Open();
 
            // Create command and fill dataset with result by using adapter.
            MySqlCommand cmd = connection.CreateCommand();
            cmd.CommandText = "Select * From Customer";
            var dataAdapter = new MySqlDataAdapter(cmd);
            var dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
 
            Console.WriteLine(dataSet.GetXml());
            connection.Close();
            Console.ReadLine();
        }
    }
}

0 件のコメント:

コメントを投稿