1. 程式人生 > >Asp.net連接數據庫及操作數據庫--入門

Asp.net連接數據庫及操作數據庫--入門

pen close 綁定 oid void area set 公共類 連接數據庫

1.創建公共類DB--4個方法。GetCon()//連接數據庫,sqlEx//執行數據庫操作, reDt//返回數據表, reDr//返回SqlDataReader對象 dr

技術分享

///<summary>連接數據庫</summary>返回SqlConnection對象
public SqlConnection GetCon()//連接數據庫,ConfigurationManager對象的AppSettings屬性值獲取配置節中連接數據庫的字符串實例化SqlConnection對象,並返回該對象
{
return new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["
ConnectionString"].ToString()); } ///<summary>執行SQL語句</summary> ///<param name="cmdstr">SQL語句</param> ///返回int類型,1:成功,0:失敗 public int sqlEx(string cmdstr)//通過 SqlCommand對象執行數據庫操作 { SqlConnection con = GetCon();//連接數據庫 con.Open();//打開連接 try { SqlCommand cmd = new SqlCommand(cmdstr, con); cmd.ExecuteNonQuery();
//執行SQL語句並返回受影響的行數 return 1; } catch (Exception e) { return 0; } finally { con.Dispose(); } } ///<summary>執行SQL查詢語句</summary> ///返回DataTable數據表 public DataTable reDt(string cmdstr)//通過SQL語句查詢數據庫中的數據,並將查詢結果存儲在DataSet數據集中,最終將該數據集中的查詢結果的數據表返回 { try { SqlConnection con = GetCon(); SqlDataAdapter da
= new SqlDataAdapter(cmdstr, con); DataSet ds = new DataSet(); da.Fill(ds); return (ds.Tables[0]);//返回DataSet對象可以作為數據綁定控件的數據源,可以對其中的數據進行編輯操作 } catch (Exception) { throw; } } ///<summary>執行SQL查詢語句</summary> ///<param name="str">查詢語句</param> ///返回SqlDataReader對象 dr public SqlDataReader reDr(string str)//將執行此語句的結果存放在一個SqlDataReader對象中,最後將這個SqlDataReader對象返回到調用處 { try { SqlConnection conn = GetCon(); conn.Open(); SqlCommand com = new SqlCommand(str, conn); SqlDataReader dr = com.ExecuteReader(CommandBehavior.CloseConnection); return dr; } catch (Exception) { throw; } }

2.使用DB方法,操作數據庫(這裏以登錄為例)

技術分享

 protected void btlogin_Click(object sender, EventArgs e)
    {

        DB db = new DB();
        string strusername = this.textusername.Text.Trim();//獲取輸入的用戶名和密碼
        string strpassword = this.textpassword.Text.Trim();
        SqlDataReader dr=db.reDr("select * from userInfo where username=‘"+strusername+"‘and password=‘"+strpassword+"");//在數據庫中select
        dr.Read();
//dr對象讀取數據集
if (dr.HasRows) { Session["username"] = dr.GetValue(1); Session["role"] = dr.GetValue(3); Response.Redirect("~/SelectObject.aspx"); } else { Response.Write("<script>alert(‘登錄失敗!‘);location=‘Login.aspx‘</script>"); } dr.Close(); }

3.在web.config文件中添加下面代碼

連接sql的登錄用戶名
連接sql的登錄密碼
數據庫名稱
服務器IP
按實際情況填寫
<configuration>
  <appSettings>
    <add key="ConnectionString" value="User id=連接sql的登錄用戶名;Password=連接sql的登錄密碼;Database=數據庫名稱;Server=服務器IP;Connect Timeout=50;Max Pool size=200;Min pool Size=5"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  
</configuration>

Asp.net連接數據庫及操作數據庫--入門