2016年7月10日 星期日

[C#] 連結 MySQL 測試與應用



安裝MySQL資料庫

http://dev.mysql.com/downloads/windows/installer/


MySQL 官方網站下載 C# 連結 MySQL 動態連結檔
http://dev.mysql.com/downloads/connector/net/6.2.html



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            testconnect();
        }

        private void testconnect()
        {
            string dbHost = "127.0.0.1";
            string dbUser = "root";
            string dbPass = "請輸入您安裝時的密碼";
            string dbName = "sakila";//注意:資料庫

            // 如果有特殊的編碼在database後面請加上;CharSet=編碼, utf8請使用utf8_general_ci
            string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            MySqlConnection conn = new MySqlConnection(connStr);


            //MySQLCommand commn = new MySQLCommand("set names big5", conn);

            // 連線到資料庫
            try
            {
                conn.Open();
                MessageBox.Show("mysql 連線成功");
            }
            catch 
            { 
                MessageBox.Show("mysql 連線失敗"); 
            }

            //=================//
            // 進行select
            // 執行查詢
            MySqlDataReader myReader = null;
            MySqlCommand myCommand = new MySqlCommand("select * from actor ", conn);//注意:資料表
            myReader = myCommand.ExecuteReader();
            //System.Console.WriteLine(myReader.ToString());

            if (myReader.HasRows)
            {
                while (myReader.Read())
                {
                    Console.WriteLine("{0}\t{1}", myReader.GetInt32(0),
                        myReader.GetString(1));
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }

        }
    }
}

參考出處:
http://www.codedata.com.tw/database/mysql-tutorial-database-abc-mysql-installation
https://blog.hsdn.net/1433.html

沒有留言:

張貼留言