c#连接mysql数据库的二种方法
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下载
补充:数据库,mysql教程