1.配置文件sql
1 <connectionStrings> 2 <add name="constr" connectionString="Data Source=.;Initial Catalog=NovelDitle;Integrated Security=True"/> 3 </connectionStrings>
2.靜態類 命名空間的引入等 數組
這裏我只寫了主要要用到的命名空間spa
1 using System.Configuration; 2 using System.Data; 3 using System.Data.SqlClient;
3.私有鏈接字符串 全局變量code
//私有鏈接字符串 private static string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
4.寫靜態方法對象
這裏的三個參數分別指的是:sql語句 存儲過程 可變參數(防sql注入)blog
①//離線查詢 返回datatable資源
1 public static DataTable ExecuteDataTable(string sql,CommandType cmdType, params SqlParameter[] par) 2 { 3 //datatable對象 4 DataTable dt = new DataTable(); 5 6 //用於處理非託管對象。某些類型的非託管對象有數量限制或很消耗系統資源。爲了及時釋放資源,使用using語句能夠確保這些資源適當地處置(dispose) 7 using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr)) 8 { 9 //存儲過程賦值 10 adapter.SelectCommand.CommandType = cmdType; 11 //判斷參數不爲空 長度>0 12 if (par != null) 13 { 14 //向數組參數中添加值 15 adapter.SelectCommand.Parameters.AddRange(par); 16 } 17 //填充數據 18 adapter.Fill(dt); 19 return dt;//返回值 20 } 21 }
②//在線查詢,返回SqlDataReader字符串
1 public static SqlDataReader ExecuteDataReader(string sql,CommandType cmdType, params SqlParameter[] par) 2 { 3 //SqlConnection要始終保持打開狀態 不能使用using釋放資源 4 SqlConnection conn = new SqlConnection(conStr); 5 6 using (SqlCommand com = new SqlCommand(sql, conn)) 7 { 8 //存儲過程賦值 9 com.CommandType = cmdType; 10 11 //判斷參數不爲空 12 if (par != null) 13 { 14 //傳入參數 15 com.Parameters.AddRange(par); 16 } 17 try 18 { 19 //若是鏈接狀態關閉 20 if (conn.State==ConnectionState.Closed) 21 { 22 //打開鏈接 23 conn.Open(); 24 } 25 //返回結果 參數:當關閉reader時也關閉SqlConnection 26 return com.ExecuteReader(CommandBehavior.CloseConnection); 27 } 28 catch (Exception) 29 { 30 //關閉鏈接 31 conn.Close(); 32 //釋放資源 33 conn.Dispose(); 34 throw;//拋出異常 35 } 36 } 37 }
③增刪改操做cmd
1 public static int ExecuteNonQuery(string sql,CommandType cmdType,params SqlParameter[] par) 2 { 3 using (SqlConnection conn = new SqlConnection(conStr)) 4 { 5 using (SqlCommand com=new SqlCommand(sql,conn)) 6 { 7 com.CommandType = cmdType; 8 9 if (par!=null) 10 { 11 com.Parameters.AddRange(par); 12 } 13 conn.Open(); 14 15 return com.ExecuteNonQuery(); 16 } 17 } 18 }
④返回單個值string
1 public static object ExecuteScalar(string sql,CommandType cmdType,params SqlParameter[] par) 2 { 3 using (SqlConnection conn = new SqlConnection(conStr)) 4 { 5 using (SqlCommand com = new SqlCommand(sql, conn)) 6 { 7 com.CommandType = cmdType; 8 9 if (par != null) 10 { 11 com.Parameters.AddRange(par); 12 } 13 conn.Open(); 14 15 return com.ExecuteScalar(); 16 } 17 } 18 }