sqlserver数据库访问帮助类
Posted 月光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver数据库访问帮助类相关的知识,希望对你有一定的参考价值。
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数据库访问帮助类的主要内容,如果未能解决你的问题,请参考以下文章
使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段