02 ASP.NET访问sql数据库(课堂学习部分)
using System.Data;
using System.Data.SqlClient;
/**
* 连接查询sql数据库
*
**/
protected void Button1_Click(object sender, EventArgs e)
{
//新建一个字符串作为连接的字符串,Data Source=.,以点号作为当前帐号进入数据库的,Catalog数据库名DB_student
string sqlconnstr = "Data Source=.;Initial Catalog=DB_student;Integrated Security=True";
SqlConnection sqlconn = new SqlConnection(sqlconnstr);//新建一个连接
sqlconn.Open();//打开连接
SqlCommand sqlcom = new SqlCommand();
sqlcom.Connection = sqlconn;
sqlcom.CommandText = "select * from T_student";//sql语句查询
SqlDataReader sqldr = sqlcom.ExecuteReader();
Label1.Text = "";
while (sqldr.Read())
{
//std_id、std_name、std_birthday、std_age为表T_student的字段
Label1.Text += sqldr["std_id"] + " ";
Label1.Text += sqldr["std_name"] + " ";
Label1.Text += sqldr["std_birthday"] + " ";
Label1.Text += sqldr["std_age"] + "<br/>";
}
sqlconn.Close();//关闭数据库
}
SUCCESS!