標籤:exec 字元 eve 字串 查詢語句 get text span pass
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對象 drpublic 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串連資料庫及操作資料庫--入門