程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> c#連接mysql數據庫的方法實例

c#連接mysql數據庫的方法實例

編輯:MySQL綜合教程

c#連接mysql教程數據庫教程的方法實例

程序代碼:

using MySQLDriverCS; // 建立數據庫連接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open(); // 執行查詢語句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select Host,User from user",DBConn); // 讀取數據MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); // 顯示數據
try{while (DBReader.Read()){
Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));}}
finally
{DBReader.Close();DBConn.Close();
} //關閉數據庫連接DBConn.Close();

實例

static void Main(string[] args)
        {
            string sqlstr = "select * from manavatar";
            MySQLConnection DBConn = new MySQLConnection(new MySQLConnectionString("192.168.0.13", "flashdata", "root", "root", 3306).AsString);
            DBConn.Open();
            //MySQLDataAdapter myadap = new MySQLDataAdapter(sqlstr, conn);
            MySQLCommand DBComm = new MySQLCommand(sqlstr,DBConn);
            MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); //DBComm.ExecuteReaderEx();
            MySQLDataAdapter DTAdapter = new MySQLDataAdapter(sqlstr,DBConn);
           
            DataSet myDataSet = new DataSet();
            DTAdapter.Fill(myDataSet,"manavatar");
         
        
            try
            {
                while (DBReader.Read())
                {
                    //Console.WriteLine("11");
                    Console.WriteLine("DBReader:{0},tttddddd:{1},tt {2}",DBReader.GetString(0), DBReader.GetString(1),DBReader.GetString(3));
                }
                Console.WriteLine("0000");
            }
            catch (Exception e)
            {
                Console.WriteLine("讀入失敗!"+e.ToString());
            }
            finally
            {
                Console.WriteLine("DBReader關閉");
                Console.WriteLine("DBConn關閉");
                DBReader.Close();
                //DBConn.Close();
            }
           
            for (int i = 0; i < myDataSet.Tables["manavatar"].Rows.Count; i++)
            {
                Console.WriteLine("{0}",myDataSet.Tables["manavatar"].Rows[2]["user"]);
            }
           
           
        }

這是一個簡單的例子。
在這裡有個問題:dataset如果沒設主鍵的話,可能會引起一些對數庫操作的問題,比如會造成updata出現錯誤

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved