c#連接mysql教程數據庫教程的二種方法
mysql提供的是一個dll文件——“mysql.data.dll”,目前我用的就是這個dll文件,將這個文件(見附件)放到網站的bin目錄下,就可以使用了。而且和sql server的用法並沒有太大的出入,只是應用的名稱不一樣而已。
代碼如下:
1.default.asp教程x:
<%@ page language="c#" autoeventwireup="true" codefile="default.aspx.cs" inherits="_default" %><form id="form1" runat="server">
<div>
<asp:table id="tbltest" runat="server">
<asp:tableheaderrow id="tblrowheader" runat="server">
<asp:tableheadercell id="tblcellheader" runat="server" text="新聞標題"></asp:tableheadercell>
</asp:tableheaderrow>
</asp:table>
</div>
</form>
2.default.aspx.cs: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 mysql.data.mysqlclient;public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
string connstr = configurationmanager.connectionstrings["connectionstring"].tostring();
mysqlconnection mysqlconn = new mysqlconnection(connstr);string sqlstr = "select name from t_document order by id desc";
mysqlconn.open();
mysqlcommand mysqlcmd = new mysqlcommand(sqlstr,mysqlconn);
mysqldatareader mysqlrdr = mysqlcmd.executereader();
while (mysqlrdr.read())
{
tablerow tr = new tablerow();
tablecell tc = new tablecell();
tc.text = mysqlrdr["name"].tostring();
tr.cells.add(tc);
tbltest.rows.add(tr);
}
}
}
方法二
在安裝文件夾下面找到mysqldriver.dll,然後將mysqldriver.dll添加引用到項目中
注:我下載的是版本是 mysqldrivercs-n-easyquerytools-4.0.1-dotnet2.0.exe
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.data.odbc;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using mysqldrivercs;
namespace mysql{
public partial class form1 : form
{
public form1()
{
initializecomponent();
}
private void form1_load(object sender, eventargs e)
{
mysqlconnection conn = null;
conn = new mysqlconnection(new mysqlconnectionstring("localhost", "inv", "root", "831025").asstring);
conn.open();
mysqlcommand commn = new mysqlcommand("set names gb2312", conn);
commn.executenonquery();
string sql = "select * from exchange ";
mysqldataadapter mda = new mysqldataadapter(sql, conn);
dataset ds = new dataset();
mda.fill(ds, "table1");
this.datagrid1.datasource = ds.tables["table1"];
conn.close();
}}
}
相關組件可以到http://dev.mysql.com/downloads/connector/net/5.0.html下載