學習ADO.NET時,你可能會遇到ADO.NET連接MySQL問題,這裡將介紹ADO.NET連接MySQL問題的解決方法,在這裡拿出來和大家分享一下。MySQL安裝好以後,點屬性,然後點查找目標,點向上一層目錄,找到BinarIEs\.Net2.0,然後將這個文件復制到你的工程目錄下,一般這樣的DLL文件會保存到bin目錄下.在代碼頁裡輸入usingMysql.Data.MysqlClIEnt;然後再在Page_Load函數裡寫MySQLConnection,在單詞寫到一半時提示就出來了,下面的就不用寫了吧?都已經出現”代碼智能完成了”,隨便寫一段代碼試試就可以了,和Sqlserver完全相似.
下面提供兩段代碼供參考,一個代碼頁,一個是Html頁:default2.ASPx.cs下ADO.Net連接MySQL代碼:
- usingSystem;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Collections;
- usingSystem.Web;
- usingSystem.Web.Security;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.Web.UI.WebControls.WebParts;
- usingSystem.Web.UI.HtmlControls;
- usingMySql.Data.MySQLClIEnt;
- publicpartialclassDefault2:System.Web.UI.Page
- {
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- stringquery="select*fromguestbook";
- MySQLConnectionmyConnection=newMySQLConnection("server=localhost;userid=root;passWord=;database=guestbook");
- MySQLCommandmyCommand=newMySQLCommand(query,myConnection);
- myConnection.Open();
- myCommand.ExecuteNonQuery();
- MySQLDataReadermyDataReader=myCommand.ExecuteReader();
- stringbookres="";
- while(myDataReader.Read()==true)
- {
- bookres+=myDataReader["id"];
- bookres+=myDataReader["user"];
- bookres+=myDataReader["pass"];
- }
- myDataReader.Close();
- myConnection.Close();
- lb1.Text=bookres;
- }
- }
default2.ASPx下的代碼
- <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default2.ASPx.cs"Inherits="Default2"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
- <HtmlXMLnsHtmlXMLns="http://www.w3.org/1999/xHtml">
- <headrunatheadrunat="server">
- <title>無標題頁</title>
- </head>
- <body>
- <ASP:labelIDASP:labelID=lb1runat=server/>
- <formidformid="form1"runat="server">
- <div>
- </div>
- </form>
- </body>
- </Html>
以上結果在visualwebDeveloper2005(速成版)下測試通過!相信在visualstudio2005中也可以通過!connector/NET5.0下載地址:http://dev.MySQL.com/downloads/connector/net/5.0.Html在做項目前需要把Mysqlconnector/net5.0裝上,然後到安裝目錄中找到MySql.Data.dll,將此文件拷貝到項目的bin目錄下然後將usingMySql.Data.MySqlClIEnt;這句紅色的語句寫到using那幾行的下面。就可以了!快速上手的正確的做法是將以前寫的SQLserver代碼改寫成MySQL的,而改寫的部分也很少,因為二者格式幾乎一樣。