連接sql server數(shù)據(jù)庫
//連接數(shù)據(jù)庫
string sqlStr = "Server=(local);User Id=sa;Pwd=;DataBase=pubs";
SqlConnection con = new SqlConnection(sqlStr);
conn.Open();
//數(shù)據(jù)庫相關(guān)操作
//關(guān)閉數(shù)據(jù)庫
conn.Close();
在Web.config 文件來配置連接數(shù)據(jù)庫的字符串
<configuration>
<appSettings>
<add key="ConnectionString" value="server=TIE\SQLEXPRESS;database=db_09;Uid=sa;password="""/>
</appSetting>
<connectionString/>
在Default.aspx 頁中,使用ConfigurationManager類獲取配置節(jié)點(diǎn)的連接字符串
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對象查詢數(shù)據(jù)庫中的記錄
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('沒有相關(guān)的記錄')</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對象操作數(shù)據(jù)
使用Command對象查詢數(shù)據(jù)
參考資料
ASP.NET 從入門到精通