[置顶] ASP.NET 连接MySql 数据库

时间:2022-07-17 13:13:16

转载自:http://www.cnblogs.com/chy710/archive/2006/09/05/495000.aspx



1.数据库MySql for .Net 驱动下载:

http://dev.mysql.com/downloads/connector/


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data.MySqlClient;

namespace MyWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = "Data Source=127.0.0.1;User ID=root;Password=QUSTDJX;DataBase=ElectClass;Charset=gb2312;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from Student", con);
MySqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
con.Close();
}


}
}


using MySql.Data 需要手动加入工程中的“引用”中去。

需要说明的是:MySql中的参数化不同于SqlServer
Sqlserver的参数化写法:
myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));
myCommand.Parameters["@Address"].Value = address.Value;

MySql的参数化写法:
 cmd.Parameters.Add(new MySqlParameter("?p_bname", MySqlDbType.VarChar, 50));
 cmd.Parameters["?p_bname"].Value = book.Text;