1. 程式人生 > >sqlserver數據庫訪問幫助類

sqlserver數據庫訪問幫助類

127.0.0.1 ret cut ram params ble and ams adp

 1 /// <summary>
 2 /// 數據庫訪問幫助類
 3 /// </summary>
 4 public static class DbHelper
 5 {
 6 private const string ConnStr = "server=127.0.0.1;database=db_test;Uid=user1;Pwd=Ps123321;";
 7 
 8 
 9 /// <summary>
10 /// 執行 增、刪、改
11 /// </summary>
12 /// <param name="sql"></param>
13 /// <param name="sqlParams"></param>
14 /// <returns></returns> 15 public static int ExecuteNonQuery(string sql, params SqlParameter[] sqlParams) 16 { 17 using (SqlConnection conn = new SqlConnection(ConnStr)) 18 { 19 conn.Open(); 20 using (SqlCommand comm = conn.CreateCommand()) 21 { 22 comm.CommandText = sql;
23 comm.CommandType = CommandType.Text; 24 if (sqlParams != null) 25 comm.Parameters.AddRange(sqlParams); 26 return comm.ExecuteNonQuery(); 27 } 28 } 29 } 30 31 /// <summary> 32 /// 返回1個查詢結果 33 /// </summary> 34 /// <param name="sql"></param>
35 /// <param name="sqlParams"></param> 36 /// <returns></returns> 37 public static object ExecuteScalar(string sql, params SqlParameter[] sqlParams) 38 { 39 using (SqlConnection conn = new SqlConnection(ConnStr)) 40 { 41 conn.Open(); 42 using (SqlCommand comm = conn.CreateCommand()) 43 { 44 comm.CommandText = sql; 45 comm.CommandType = CommandType.Text; 46 if (sqlParams != null) 47 comm.Parameters.AddRange(sqlParams); 48 return comm.ExecuteScalar(); 49 } 50 } 51 } 52 53 /// <summary> 54 /// 返回查詢,返回結果集 55 /// </summary> 56 /// <param name="sql"></param> 57 /// <param name="sqlParams"></param> 58 /// <returns></returns> 59 public static DataTable ExecuteQuery(string sql, params SqlParameter[] sqlParams) 60 { 61 using (SqlConnection conn = new SqlConnection(ConnStr)) 62 { 63 conn.Open(); 64 using (SqlCommand comm = conn.CreateCommand()) 65 { 66 comm.CommandText = sql; 67 comm.CommandType = CommandType.Text; 68 if (sqlParams!=null) 69 comm.Parameters.AddRange(sqlParams); 70 using (SqlDataAdapter adp = new SqlDataAdapter(comm)) 71 { 72 DataSet ds = new DataSet(); 73 adp.Fill(ds); 74 return ds.Tables[0]; 75 } 76 } 77 } 78 } 79 }

sqlserver數據庫訪問幫助類