1,使用C#進行連接數據庫操作時一般會用到SqlHelper
這個封裝的類我剛開始自己學習的時候,連接數據庫總是一坨代碼,不僅難看,而且不好改。
看了有關傳智的一些資料後,我慢慢改正了自己一些些代碼的缺點,現在我就來說一下有關SqlHelper的具體封裝。
2.SqlHelper的具體封裝
因爲一般SqlHelper會在整個項目中使用,所以一般會把它寫成靜態類。
(1)執行insert/delete/update的方法
public static int ExecuteNonQuery(string sql,CommandType type,params SqlParamter[] para)
{}
這個方法有3個參數,分別是sql(所需的sql語句),type(選擇是普通的SQL語句還是存儲過程),para(這個是傳入的多個可變參數)
返回值是int類型,返回影響的行數
using(SqlConnection conn=new SqlConnection(connStr))
{
using(SqlCommand cmd=new SqlCommand(sql,conn))
{
//再下一步寫裏面的內容
}
}
這是方法裏面的內容
這裏用到了SqlConnection和SqlCommand,分別是數據連接函數和數據命令函數
前者是用於連接數據庫,傳入的參數connStr就是連接字符串
後者用於使用Sql語句對數據庫的數據進行處理
using的作用是到結束時釋放資源,就相當於Dispose和Close
{
cmd.CommandType=type;
if(para!=null)
{
cmd.Paramter.AddRange(para);
}
conn.Open();
return cmd.ExecuteNonQuery();
}
這時寫在SqlCommand裏面的內容
要先判斷傳入的可變參數是否爲空,不爲空就將傳入的參數加到Sql語句中
在這裏要注意,conn越晚打開越好,一般是在執行查詢函數之前打開。
最後返回 執行的查詢函數得到的結果(也就是影響的行數)
(2)執行返回單個值得方法
因爲與前一個方法基本一樣,就直接貼代碼了
public static object ExecuteScalar(string sql, CommandType type, params SqlParameter[] para)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = type;
if (para != null)
{
cmd.Parameters.AddRange(para);
}
conn.Open();
return cmd.ExecuteScalar();
}
}
}
(3)返回SqlDataReader的方法
public static SqlDataReader ExecuteScalar(string sql, CommandType type, params SqlParameter[] para)
{
SqlConnection conn = new SqlConnection(connStr);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = type;
if (para != null)
{
cmd.Parameters.AddRange(para);
}
try
{
conn.Open();
return cmd.ExecuteReader(CommandBehacior.CloseConnection);
}
catch
{
conn.Close();
conn.Dispose();
throw;
}
}
}
這裏只說一下不同的地方,
爲什麼SqlConnection沒有使用using?
因爲如果使用返回的Reader對象的話,SqlConnection就必須保持打開,
而using在結束時就釋放資源了。
爲什麼使用try。。。catch?
因爲如果直接返回Reader對象的話,SqlConnection對象一直保持打開狀態,
無法將其關閉。
CommandBehacior.CloseConnection
的作用就是在Reader對象使用完後,關閉SqlConnection,(4)返回DataTable對象
public static DataTable ExecuteDataTable(string sql, CommandType type, params SqlParameter[] para)
{
DataTable dt = new DataTable();
using (SqlDataAdapter adapter=new SqlDataAdapter(sql,connStr))
{
adapter.SelectCommand.CommandType = type;
if (para != null)
{
adapter.SelectCommand.Parameters.AddRange(para);
}
adapter.Fill(dt);
return dt;
}
}
不用打開連接,SqlDataAdapter內部會自動打開
adapter的Fill方法是將數據從內存中讀到DataTable
3.有關連接字符串的小知識
它的作用就是打開數據庫的一把鑰匙!
一般將它定義在App.config中
寫法一般有兩種:
(1)Data Source=(local);Initial Catalog=這裏寫數據庫名稱;Integrated Security=true;
這種方法是連接window登陸的鑰匙
(2)Data Source=(local);Initial Catalog=這裏寫數據庫名稱;User ID=這裏寫用戶名;Password=這裏寫密碼
這種方法是連接Sql Server身份驗證的鑰匙.