asp.net 連接數據庫,操作數據庫主要需要兩個類,一個是SqlConnection,一個是SqlCommand
SqlConnection用於連接數據庫,打開數據庫,關閉數據庫。
連接數據庫需要特定格式,特定參數的字符串,如代碼中寫的,服務器地址,數據庫名稱,用戶名密碼,以及其他參數
SqlCommand用於操作數據庫,先創建基於一個特定SqlConnection對象的SqlCommand對象,通過ExecuteNonQuery方法執行給定的sql語句。
增刪改都可以只是這樣就操作成功,但查詢因為需要把數據讀到一個地方,所以有一個新的對象出現了:SqlDataReader
通過SqlCommand對象的ExecuteReader方法得到一個SqlDataReader對象,SqlDataReader對象包含數據集,通過對SqlDataReader對象遍歷即可取出查詢的數據。
public void openDatabase() { conn = new SqlConnection(); //conn.ConnectionString = "Integrated Security=SSPI;Data Source=(local);initial catalog=test;User ID ='sa';password=123456"; conn.ConnectionString = "Integrated Security=SSPI;Data Source=(local);initial catalog=test"; if (conn.State == ConnectionState.Closed) { conn.Open(); } } public void execute(String sql) { openDatabase(); cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); conn.Close(); } protected void Page_Load(object sender, EventArgs e) { ResponseBean responseBean = new ResponseBean(Request); var sign = GetSign(responseBean).ToLower(); if (responseBean.p4_zfstate == "1" && sign.Equals(responseBean.p10_sign)) //if (responseBean.p4_zfstate == "1") { //服務器操作 Response.Write("Success"); //exec [RYTreasureDB].[dbo].[WEB_JFTNotify] 'JFTAPP20180803161806183015224' sql = "exec [RYTreasureDB].[dbo].[WEB_JFTNotify] '" + responseBean.p2_ordernumber + "'"; execute(sql); } else { Response.Write("無參數或者參數不正確"); // sql = "update [RYTreasureDB].[dbo].[OnLineOrder] set OrderStatus=1 where OrderID='" + "JFTAPP20180803144628796685254" + "'and isCalc=0"; // execute(sql); } }// function Page_Load
上面一段代碼主要邏輯功能在
Page_Load函數,而我通過這里連接數據庫之后執行了一個存儲過程。這樣很多問題就可以通過修改存儲過程解決,不用經常修改代碼
上面conn.ConnectionString寫在代碼里也是不好的,最好寫在配置文件Web.config中。
在<appSettings>添加配置項<add key="ConnectionString" value="Integrated Security=SSPI;Data Source=(local);initial catalog=test" />
通過conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]獲取即可;
參考文章https://blog.csdn.net/lqadam/article/details/50865024