06 Sep 2010 
Support Center » Knowledgebase » How to connect to MySQL database from ASP.NET? 如何設定ASP.NET連接MySQL數據庫?
 How to connect to MySQL database from ASP.NET? 如何設定ASP.NET連接MySQL數據庫?
Solution Below is the sample codes for ASP.NET connecting MySQL database:
以下是參考程式碼關於ASP.NET連接 MySQL數據庫:

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Odbc" %>
<%@ Page Language="C#" %>
<script runat="server">
public void Page_Load(Object sender, EventArgs e) {
    DataTable dtRecords = GetDataTable("SELECT * FROM test");
    foreach(DataRow dr in dtRecords.Rows) {
        Response.Write(dr["fielda"].ToString() + " " + dr["fieldb"].ToString() + "<br/>");
    }
}
private static string GetConnection() {
    return "DRIVER={MySQL ODBC 5.1 Driver};Server=localhost;Database=mysqldbdemo;UID=mysqldbdemo;PASSWORD=VmSPqRQh;";
}
public static DataTable GetDataTable(string sql) {
    DataTable rt = new DataTable();
    DataSet ds = new DataSet();
    OdbcDataAdapter da = new OdbcDataAdapter();
    OdbcConnection con = new OdbcConnection(GetConnection());
    OdbcCommand cmd = new OdbcCommand(sql, con);
    da.SelectCommand = cmd;
    da.Fill(ds);
    try {
        rt = ds.Tables[0];
    }
    catch {
        rt = null;
    }
    return rt;
}
</script>


Article Details
Article ID: 39
Created On: 08 Dec 2009 11:55 AM

 This answer was helpful  This answer was not helpful

 Back
 Login [Lost Password] 
Email:
Password:
Remember Me:
 
 Search
 Article Options
Home | Register | Submit a Ticket | Knowledgebase | Downloads
Language:

Help Desk Software By Kayako eSupport v3.60.04