标签:
App.config文件
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 5 </startup> 6 <connectionStrings> 7 <add connectionString="Data Source = .; Initial Catalog = mysql; Integrated Security = True;" name="conStr" /> 8 </connectionStrings> 9 </configuration>
sqlHelper封装类库代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 //新建一个App.confit文件,引用下面两个命名空间 7 using System.Configuration; 8 using System.Data.SqlClient; 9 10 namespace 封装 11 { 12 public class SqlHelper 13 { 14 //读取连接字符串 15 private static readonly string str = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; 16 //三个方法,关键是第三个方法,查询,条件判断比较多 17 /// <summary> 18 /// 此方法可以做增删改 19 /// </summary> 20 /// <param name="sql">sql语句</param> 21 /// <param name="ps">sql语句中的参数</param> 22 /// <returns>返回受影响的行数,int类型</returns> 23 private static int ExecuteNonQuery(string sql, params SqlParameter[] ps) 24 { 25 using (SqlConnection con = new SqlConnection(str)) 26 { 27 using (SqlCommand cmd = new SqlCommand(sql, con)) 28 { 29 con.Open(); 30 if (ps != null) 31 { 32 cmd.Parameters.AddRange(ps); 33 } 34 35 return cmd.ExecuteNonQuery(); 36 } 37 } 38 } 39 /// <summary> 40 /// 该方法用在查询上 41 /// </summary> 42 /// <param name="sql">sql语句</param> 43 /// <param name="ps">sql语句中的参数</param> 44 /// <returns>返回首行首列,object类型</returns> 45 private static object ExecuteScalar(string sql, params SqlParameter[] ps) 46 { 47 using (SqlConnection con = new SqlConnection(str)) 48 { 49 using (SqlCommand cmd = new SqlCommand(sql, con)) 50 { 51 con.Open(); 52 if (ps != null) 53 { 54 cmd.Parameters.AddRange(ps); 55 } 56 return cmd.ExecuteScalar(); 57 } 58 } 59 } 60 /// <summary> 61 /// 该方法用于查询,读数据 62 /// </summary> 63 /// <param name="sql">sql语句</param> 64 /// <param name="ps">sql语句中的参数</param> 65 /// <returns>返回sqldatareader对象,里面有数据</returns> 66 private static SqlDataReader ExecuteReader(string sql, params SqlParameter[] ps) 67 { 68 //这地方不用using,因为不知道什么时候释放 69 SqlConnection con = new SqlConnection(str); 70 using (SqlCommand cmd = new SqlCommand(sql,con)) 71 { 72 if (ps!=null) 73 { 74 cmd.Parameters.AddRange(ps); 75 } 76 try 77 { 78 con.Open(); 79 //这个重载会datareader关闭时,自动关闭connection 80 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); 81 } 82 catch (Exception ex) 83 { 84 con.Close(); 85 con.Dispose(); 86 throw ex; 87 } 88 } 89 } 90 } 91 }
标签:
原文地址:http://www.cnblogs.com/Jacklovely/p/5657759.html