วันอังคารที่ 4 มิถุนายน พ.ศ. 2556

การเขียนโปรแกรม C# .Net ติดต่อ MySQL


การใช้งานฐานข้อมูล MySQL ด้วย C# เรื่องที่สรุปก็มีในส่วนของการเชื่อมต่อฐานข้อมูล, การใช้ mysql connector/net ในการช่วยจัดการฐานข้อมูล MySQL, รวมถึงตัวอย่างการใช้งานพื้นฐานอย่างการ Insert

การ เตรียมความพร้อม

  1. ติดตั้ง MySQL ให้เรียบร้อย
  2. ดาวน์โหลด mysql connector/net ซึ่งเป็นตัวช่วยในการใช้งาน MySQL ด้วยภาษา C# ให้ง่ายขึ้น http://dev.mysql.com/downloads/connector/net/6.2.html
  3. ทำการติดตั้ง mysql connector/net  http://dev.mysql.com/doc/refman/5.1/en/connector-net-installation-windows.html

เริ่มการใช้งานฐานข้อมูล MySQL ด้วย C# ด้วย Microsoft Visual C# 2010 Express

  1. เปิดโปรแกรม Microsoft Visual C# ขึ้นมา
  2. ทำการสร้าง Project ใหม่
  3. ทำการ add reference to: MySql.Data
    - คลิกขวาที่ Solution Explorer แล้วเลือก Add Reference…
    mysql_connector_net_add_reference_to_MySql_Data_2.jpg
    - ที่แทบ .NET เลือก MySql.Data
    mysql_connector_net_add_reference_to_MySql_Data.jpg
  4. เรียกใช้งานโดย
    using MySql.Data.MySqlClient;
    using System.Configuration;

การเชื่อมต่อฐานข้อมูล MySQL ด้วย C# ด้วย Microsoft Visual C#

หลักของการเชื่อมต่อและใช้งานก็คือ
  1. connection string : เป็นส่วนกำหนดค่าว่า Server อะไร, ฐานข้อมูลชื่ออะไร, ชื่อผู้ใช้และรหัสผ่านในการเชื่อมต่อ 
    เลือกเมนู  Project > Add New Item...
    เลือก Application Configuration File
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="ConnectionString" value="SERVER=localhost;DATABASE=HirePurchase;UID=root;PASSWORD=12345;"/>
      </appSettings>
    </configuration>
  2. MySqlConnection object เป็นตัวจัดการในการเชื่อมต่อกับฐานข้อมูล โดย MySqlConnection constructor จะรับ connection string เป็นพารามิเตอร์
            string ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
            MySqlConnection Conn;
            MySqlCommand com;
            MySqlTransaction tr;



                 Conn = new MySqlConnection(ConnectionString);
                if (Conn.State == ConnectionState.Open)
                {
                    Conn.Close();
                }


             
  3. เริ่มการเชื่อมต่อ
    Conn.Open();
  4. ในการทำงานคำสั่ง SQL นั้นจะทำผ่าน MySqlCommand object
                string sqlBranch;
                sqlBranch = "SELECT * FROM Branch ORDER BY BranchID";

                MySqlDataReader dr;
                com = new MySqlCommand();
                com.CommandType = CommandType.Text;
                com.CommandText = sqlBranch;
                com.Connection = Conn;
  5. ปิดการเชื่อมต่อ
    connection.Close();
โค้ดตัวอย่างของการเชื่อมต่อ
            
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 System.Drawing.Printing;

using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using System.Configuration;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        string ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
        MySqlConnection Conn;
        MySqlCommand com;
        MySqlTransaction tr;
        StringBuilder sb;

        public Form1()
        {
            InitializeComponent();
        }

            
        private void Form1_Load(object sender, EventArgs e)
        {
            /*dataGridView2.ColumnCount = 1;
            dataGridView2.Columns[0].HeaderText = "Data";
            dataGridView2.Columns[0].Width = 300;
             */

            Conn = new MySqlConnection(ConnectionString);
            if (Conn.State == ConnectionState.Open)
            {
                Conn.Close();
            }

            Conn.Open();
            ShowData();
            FormatDgvBranchList();

        }

        private void ShowData()
        {
                string sqlBranch;
                sqlBranch = "SELECT * FROM Branch ORDER BY BranchID";

                MySqlDataReader dr;
                com = new MySqlCommand();
                com.CommandType = CommandType.Text;
                com.CommandText = sqlBranch;
                com.Connection = Conn;
            dr = com.ExecuteReader();
            if (dr.HasRows)
            {
                DataTable dt = new DataTable();
                dt.Load(dr);

                dataGridView2.DataSource = dt;
            }
            else
            {
                dataGridView2.DataSource = null;
            }
            dr.Close();
        }

        private void FormatDgvBranchList()
        {
            if (dataGridView2.RowCount > 0)
            {
                dataGridView2.Columns[0].HeaderText = "รหัสสาขา";
                dataGridView2.Columns[1].HeaderText = "ชื่อสาขา";

                dataGridView2.Columns[0].Width = 100;
                dataGridView2.Columns[1].Width = 150;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView2.Rows.Add(textBox1.Text);
            textBox1.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Pritn document
            PrintDocument printDoc = new PrintDocument();
            printDoc.DocumentName = "Test Document";
            printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);

            // Print dialog
            //PrintDialog printDlg = new PrintDialog();
           // printDlg.Document = printDoc;
            //if (printDlg.ShowDialog() == DialogResult.OK)
            printDoc.Print();
        
        }

        void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            // Print Header
            e.Graphics.DrawString("Header Report Title", new Font("Arial", 20), Brushes.Black, 10, 10);
            e.Graphics.DrawLine(Pens.Gray, 10, 50, 830, 50);

            // Print content
            int position = 130;
            e.Graphics.DrawString("-- Data from Data Grid View --", new Font("Arial", 16), Brushes.Black, 10, 100);
            foreach (DataGridViewRow item in dataGridView2.Rows)
            {
                e.Graphics.DrawString((string)item.Cells[0].Value, new Font("Arial", 10), Brushes.Black, 10, position);
                position += 20;
            }

            // Print Footer
           // e.Graphics.DrawLine(Pens.Gray, 10, 1050, 830, 1050);
          //  e.Graphics.DrawString("Footer Report Title", new Font("Arial", 20), Brushes.Black, 10, 1060);
        }
    }
}
ผลลัพธ์ที่ได้

2 ความคิดเห็น:

  1. มีตัวอย่าง Output รึป่าวคับ

    ตอบลบ
    คำตอบ
    1. ผมได้เพิ่มส่วนของ Output ให้แล้วนะครับด้านล่างสุด แต่ปุ่ม เพิ่ม ยังใช้งานไม่ได้นะครับ ปุ่ม พิมพ์ ใช้ได้ครับ

      วัตถุประสงค์หลักคือ ต้องการเขียนโปรแกรม C# .net กับ MySQL ครับ

      ลบ