WebForm连接数据库实例
登錄頁面:用戶名文本框、密碼文本框、登錄按鈕
當用戶名密碼輸入正確,點擊確定可以跳轉到下一個頁面
我們需要先引入命名空間:
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
頁面代碼:
? ? ? ? ? ?
? ? ? ? ? ? string name = TextBox1.Text.Trim();//獲取到文本框中的用戶名
? ? ? ? ? ? string pwd = TextBox2.Text;//獲取到文本框中的密碼
? ? ? ? ? ? //連接數據庫字段
? ? ? ? ? ? string sqlcoon = "Data Source=.;Initial Catalog=logis;Integrated Security=True";
? ? ? ? ? ? string sql = string.Format("select count(*) from User1 where Account=@Account and Password=@Password_");//查詢是否有該條記錄,根據賬戶密碼
? ? ? ? ? ? SqlParameter[] par = {
? ? ? ? ? ? ? ? new SqlParameter("@Account",name),
? ? ? ? ? ? ? ? ? ?new SqlParameter("@Password_",pwd)
?
? ? ? ? ? ? };
? ? ? ? ? ? using (SqlConnection con = new SqlConnection(sqlcoon))//SqlConnection連接,用using釋放連接
?
? ? ? ? ? ? {
? ? ? ? ? ? ? ? using (SqlCommand com = new SqlCommand(sql, con))//SqlCommand連接,用using釋放連接
?
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? com.Parameters.AddRange(par);
? ? ? ? ? ? ? ? ? ? //打開連接
? ? ? ? ? ? ? ? ? ? con.Open();
?
? ? ? ? ? ? ? ? ? ? int resert = Convert.ToInt32(com.ExecuteScalar());
? ? ? ? ? ? ? ? ? ? //關閉連接
? ? ? ? ? ? ? ? ? ? //con.Close();
? ? ? ? ? ? ? ? ? ? //釋放連接
? ? ? ? ? ? ? ? ? ? // con.Dispose();
? ? ? ? ? ? ? ? ? ? if (resert > 0)
? ? ? ? ? ? ? ? ? ? {
?
? ? ? ? ? ? ? ? ? ? ? ? Response.Redirect("開票界面.aspx");
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? Label1.Text = "賬戶名或密碼錯誤!";
?
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }?
知識點:
1.連接數據庫字段
//連接數據庫字段
? ? ? ? ? ? string sqlcoon = "Data Source=.;Initial Catalog=logis;Integrated Security=True";
連接數據庫字段是根據自己的數據庫連接來寫的。其中server表示運行Sql Server的計算機名,由于程序和數據庫系統是位于同一臺計算機的,所以我們可以用.(或localhost)取代當前的計算機名。Date Source表示所使用的數據庫名(logis)。integrated security=true 的意思是集成驗證,也就是說使用Windows驗證的方式去連接到數據庫服務器。這樣方式的好處是不需要在連接字符串中編寫用戶名和密碼,從一定程度上說提高了安全性。
2.查詢語句
?string sql = string.Format("select count(*) from User1 where Account=@Account and Password=@Password_");
這樣寫數據庫是為了防止惡意攻擊數據庫。
3.SqlParameter
? SqlParameter[] par = {
? ? ? ? ? ? ? ? new SqlParameter("@Account",name),
? ? ? ? ? ? ? ? ? ?new SqlParameter("@Password_",pwd)
?
? ? ? ? ? ? };
SqlParameter對象在C#中獲取存儲過程的返回值。利用Add方法和AddRange方法來使用。
4.使用using釋放資源
例如:Using(){}
using釋放的是非托管資源
close()只是關閉連接,但是通道沒有銷毀,dispose()不僅把連接給關閉了,而且把通道也給銷毀了。
可以用using來代替dispose()
5.ExecuteScalar
SqlCommand對象的三種方法:
(1)判斷增刪改的ExcuteNonQUery()方法,會在增刪改成功之后返回數字?
(2)讀取sql查詢語句的內容使用SqlDataReader()方法
(3)SqlCommand.ExecuteScalar()方法的作用就是
執行查詢,并返回查詢所返回的結果集中第一行的第一列。忽略其他行或列,返回值為object類型
總結
以上是生活随笔為你收集整理的WebForm连接数据库实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WindowsAPI-Findwindo
- 下一篇: 解决:Request header fi