首先在自己的SQLsever中建立一个叫test1的数据库,
(我的数据库是用的Windows身份验证所以连接字符串后面没有SQLSever的账号和密码)
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn =new SqlConnection("Integrated Security=SSPI;Data Source=(local);initial catalog=test1");
Response.Write("状态1:" + conn.State.ToString());
conn.Open();
Response.Write("状态2:" + conn.State.ToString());
conn.Close();
Response.Write("状态3:" + conn.State.ToString());
}
运行效果
10.25更新
改进版,从数据库中读取数据
1.数据库
2.demo
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Data Source=(local);initial catalog=test1");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from U_table", conn);
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Response.Write("<center><tr><td></br>"
+ "</td>用户名:<td>" + dataReader["username"].ToString()
+ "</td>密码:<td>" + dataReader["password"].ToString() + "</td></br></tr></center>");
}
conn.Close();
}
3.显示效果
更新10.30
更新版,增加添加数据模块
protected void btn_insert_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Data Source=(local);initial catalog=test1");
conn.Open();
string str_user = txt_user.Text;
string str_pwd = txt_pwd.Text;
//插入insert into U_table(username,password) values('2131','3131');
SqlCommand cmd3 = new SqlCommand("insert into U_table(username,password) values(" + str_user + "," + str_pwd + ")", conn);
int result = cmd3.ExecuteNonQuery();
if (result==1)
{
tishi.Text = "插入成功";
}
else
{
tishi.Text = "插入失败";
}
}//btn_insert_Click
效果