mysql C# reader

iamzxf發表於2015-06-15


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

namespace mySQLReader
{
    class Program
    {
        static void Main(string[] args)
        {
            string constr = "server=localhost;User Id=root;password=root;Database=users";
            MySqlConnection mycon = new MySqlConnection(constr);
            try
            {
                mycon.Open();
                string sltStr = "select id, name from user";
                string sltResult = "";
                int i = 1;
                MySqlCommand sqlcmd = new MySqlCommand(sltStr, mycon);
                MySqlDataReader reader = sqlcmd.ExecuteReader();

                Console.WriteLine("基本資料查詢結果:");

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        sltResult += "第" + i + "條記錄:" + reader["id"].ToString() + reader["name"].ToString() + "\n";
                        i++;
                    }
                    Console.WriteLine(sltResult);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            mycon.Close();
            Console.WriteLine("資料庫正常關閉");
            Console.ReadLine();
        }
    }
}



相關文章