连接sql server数据库
//连接数据库
string sqlStr = "Server=(local);User Id=sa;Pwd=;DataBase=pubs";
SqlConnection con = new SqlConnection(sqlStr);
conn.Open();
//数据库相关操作
//关闭数据库
conn.Close();
在Web.config 文件来配置连接数据库的字符串
<configuration>
<appSettings>
<add key="ConnectionString" value="server=TIE\SQLEXPRESS;database=db_09;Uid=sa;password="""/>
</appSetting>
<connectionString/>
在Default.aspx 页中,使用ConfigurationManager类获取配置节点的连接字符串
public SqlConnection getConnection
{
string mySqlString = ConfigurationManager.AppSetting["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(mySqlString);
return myConn;
}
在Default.aspx页中编写查询的代码
protected void btnSelect_Click(object sender, EvetArgs e)
{
if(this.txtname.Text != "")
{
SqlConnection myConn = GetConnection();
myConn.Open();
//使用Command对象查询数据库中的记录
string sqlStr = "select * from tb_Student where Name=@Name";
SqlCommand myCmd = new SqlCommand(sqlStr,myConn);
myCmd.Parameters.Add("@Name",SqlDbType.VarChar,20).Value = this.txtName.Text.Trim();
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if(myDs.Tables[0].Rows.count > 0)
{
GridView1.DataSource = myDs;
GridView1.DataBind();
}
else
{
Response.Write("<script>alert('没有相关的记录')</script>");
}
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}else
{
this.bind();
}
}
插入记录
protected void btnAdd_Click(object sender, EventArgs e){
if(this.txtClass.Text != "")
{
SqlConnection myConn = getConnection;
myConn.Open();
string sqlStr = "insert into tb_Class(ClassName) values(" + this.txtClass.Text.Trim() + "")";
SqlCommand myCmd = new SqlCommand(sqlStr,myConn);
myCmd.ExecuteNonQuery();
myCmd.Close();
this.bind();
}else{
this.bind();
}
}
使用Command对象操作数据
使用Command对象查询数据
参考资料
ASP.NET 从入门到精通