C# MySQL DataAdapter

iamzxf發表於2015-06-15


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;

namespace mysqlDataAdapter
{
    class Program
    {
        static void Main(string[] args)
        {
            string constr = "server=localhost;User Id=root;password=root;Database=users";
            MySqlConnection mycon = new MySqlConnection(constr);

            try
            {
                string sltStr = "select id, name from user";
                MySqlCommand sqlCmd = new MySqlCommand(sltStr, mycon);
                MySqlDataAdapter sda = new MySqlDataAdapter(sqlCmd);

                DataSet ds = new DataSet();
                sda.Fill(ds);
                string sltResult = "";

                DataTable dt = ds.Tables[0];

                Console.WriteLine("表查詢結果如下:");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sltResult += "第" + i + "條記錄" + dt.Rows[i][0].ToString() + "\t" + dt.Rows[i][1].ToString() + "\n";
                    
                }
                Console.Write(sltResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("資料庫正常關閉");
            Console.ReadLine();
        }
    }
}



相關文章