asp.net連接Mysql(connector/net 5.0)
Mysql的connector/net5.0下載地址:
http://dev./get/Downloads/Connector-Net/mysql-connector-net-5.0.6.zip/from/pick
安裝好以后,點(diǎn)屬性,然后點(diǎn)查找目標(biāo),點(diǎn)向上一層目錄,找到Binaries\.NET 2.0,然后將這個(gè)文件復(fù)制到你的工程目錄下,一般這樣的DLL文件會(huì)保存到bin目錄下.
在代碼頁里輸入using Mysql.Data.MysqlClient;然后再在Page_Load函數(shù)里寫MysqlConnection,在單詞寫到一半時(shí)提示就出來了,下面的就不用寫了吧?都已經(jīng)出現(xiàn)”代碼智能完成了”,隨便寫一段代碼試試就可以了,和Sqlserver完全相似.
下面提供兩段代碼供參考,一個(gè)代碼頁,一個(gè)是HTML頁:
default2.aspx.cs下的代碼:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string query = "select * from guestbook";
MySqlConnection myConnection = new MySqlConnection("server=localhost;user id=root;password=;database=guestbook");
MySqlCommand myCommand=new MySqlCommand(query,myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
MySqlDataReader myDataReader = myCommand.ExecuteReader();
string bookres="";
while (myDataReader.Read()==true)
{
bookres+=myDataReader["id"];
bookres+=myDataReader["user"];
bookres += myDataReader["pass"];
}
myDataReader.Close();
myConnection.Close();
lb1.Text = bookres;
}
}
default2.aspx下的代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml" >
<head runat="server">
<title>無標(biāo)題頁</title>
</head>
<body>
<asp:label ID=lb1 runat=server/>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
以上結(jié)果在visual web Developer2005(速成版)下測試通過!相信在visual studio 2005中也可以通過!
connector/NET 5.0下載地址:http://dev./downloads/connector/net/5.0.html
在做項(xiàng)目前需要把Mysql connector/net 5.0裝上,然后到安裝目錄中找到MySql.Data.dll,將此文件拷貝到項(xiàng)目的bin目錄下然后將using MySql.Data.MySqlClient; 這句紅色的語句寫到using那幾行的下面。就可以了!
快速上手的正確的做法是將以前寫的SQLserver 代碼改寫成mysql的,而改寫的部分也很少,因?yàn)槎吒袷綆缀跻粯?
注:去MySQL的網(wǎng)站上 下載一個(gè) 專用的連接庫 ,然后把那個(gè) DLL文件引用進(jìn)項(xiàng)目。其它的連法用SQL Server 一樣的。只是 SQLConnection改成 MySQLConnection 其它DataReader、Command等相應(yīng)改變!