Default.aspx对应的cs文件内容
mysql官网下载 mysql-connector-net ,目前版本6.4.5,安装好后,将安装目录下的mysql.data.dll拷贝到asp.web工程目录的Bin目录,在visual web developer或者vs2008里的解决方案里新建Bin目录并添加mysql.data.dll文件即可使用了(ususing MySql.Data.MySqlClient;)
1. MySqlConnection()// mysql连接
2. MySqlCommand()//sql命令:sql语句
3. ExecuteReader() //读取结果,表内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
public partial class _Default : System.Web.UI.Page
{
public void MessageBox(string strText ,Page objPage)
{
string scriptStr,alertStr;
alertStr = "window.alert( ' "+strText+ " ') ";
scriptStr = " <script> "+alertStr+ " </script> ";
objPage.RegisterClientScriptBlock( "failure ",IidScript);
}
protected void Page_Load(object sender, EventArgs e)
{
string connStr = "server=127.0.0.1;uid=root;" + "pwd=123456;database=test;";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Response.Write("hello");
conn.Open();
//DataTable table = conn.GetSchema("MetaDataCollections");
//DataTable table = conn.GetSchema("UDF");
//DisplayData(table);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
//出错情况下才会进入
switch (ex.Number)
{
case 0:
MessageBox("Cannot connect to server. Contact administrator",Page);
break;
case 1045:
MessageBox("Invalid username/password, please try again",Page);
break;
}
}
Response.Write("open database ok!");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "testtable";
cmd.Connection = conn;
cmd.CommandType = CommandType.TableDirect;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Response.Write(reader[0] ); //第一字段
Response.Write(" " + reader[1] );
//第二字段
}
conn.Close();
} //end page_load()
}
//更多的数据库操作api参考mysql-connection-net安装包里的mysql.data.chm帮助文档
- 1楼leihengxin4小时前
- 顶一下。