文章目錄
using
System;
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
using
MySQLDriverCS;
public
partial class
_Default : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
MySQLConnection conn = null;
conn = new MySQLConnection(new
MySQLConnectionString("127.0.0.1", "Dvbbs", "root",
"123456").AsString);
conn.Open();
MySQLCommand commn = new MySQLCommand("set names
gb2312",conn);
commn.ExecuteNonQuery();
string sql = "select
title,topicID, boardId
,dateandtime,hits from Dv_topic order by dateandtime
desc limit 10";
MySQLDataAdapter mda = new MySQLDataAdapter(sql,conn);
DataSet ds = new
DataSet();
mda.Fill(ds, "table1");
this.Repeater1.DataSource = ds;
this.Repeater1.DataBind();
conn.Close();
}
}
就這樣就可以實現在.NET環境下對MySQL資料的訪問。在這之前還要做一些準備,下載MySQLDriverCS,安裝,在安裝資料夾下面找到MySQLDriver.dll,然後將MySQLDriver.dll添加引用到項目中就OK了。也許你對這行代碼
MySQLCommand commn = new MySQLCommand("set names
gb2312",conn);
commn.ExecuteNonQuery();
不太理解。這是因為如果沒有這句話從資料庫裡讀出的資料中如果有中文將顯示亂碼,只要把這個語句“set names
gb2312”當作SQL語句執行一遍就可以了。