标签:
简单的SQLHelper类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Configuration; 7 using System.Data.SqlClient; 8 using System.Data; 9 10 namespace MyDBHelper 11 { 12 public class SQLHelper 13 { 14 //获取连接字符串,从配置文件中 15 //不加密 16 private readonly string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString; 17 18 //执行非查询语句 返回受影响的行数 19 public static int ExecuteNonQuery(string commandText,params SqlParameter[] parameters) 20 { 21 using (SqlConnection conn = new SqlConnection()) 22 { 23 using (SqlCommand cmd = new SqlCommand(commandText,conn)) 24 { 25 cmd.CommandType = CommandType.Text;//默认是CommandType.Text 26 if (parameters.Length > 0) 27 { 28 cmd.Parameters.AddRange(parameters); 29 } 30 conn.Open(); 31 return cmd.ExecuteNonQuery(); 32 } 33 } 34 } 35 /// <summary> 36 /// 查询符合SQL语句的数据,填充数据表中 37 /// </summary> 38 /// <param name="commandText">实质是sql语句</param> 39 /// <param name="parameters">sql语句中的参数</param> 40 /// <returns></returns> 41 public static DataTable ExecuteDataTable(string commandText,params SqlParameter[] parameters) 42 { 43 using (SqlConnection conn = new SqlConnection()) 44 { 45 conn.Open(); 46 using (SqlCommand cmd = conn.CreateCommand())//可以通过conn创建SqlCommand对象,也可以直接new 47 { 48 cmd.CommandText = commandText; 49 cmd.CommandType = CommandType.Text; 50 cmd.Parameters.AddRange(parameters); 51 DataSet ds = new DataSet(); 52 SqlDataAdapter adapter = new SqlDataAdapter(cmd); 53 adapter.Fill(ds); 54 return ds.Tables[0]; 55 } 56 } 57 } 58 /// <summary> 59 /// 执行SQL语句查询 返回结果集中的第一行第一列的值 60 /// </summary> 61 /// <param name="commandText">SQL语句</param> 62 /// <param name="parameters">参数。可变参数</param> 63 /// <returns></returns> 64 public static object ExecuteScalar(string commandText,params SqlParameter[] parameters) 65 { 66 using(SqlConnection conn=new SqlConnection()) 67 { 68 conn.Open(); 69 using(SqlCommand cmd=conn.CreateCommand()) 70 { 71 cmd.CommandText=commandText; 72 cmd.CommandType=CommandType.Text; 73 cmd.Parameters.AddRange(parameters); 74 return cmd.ExecuteScalar(); 75 } 76 } 77 } 78 } 79 }
标签:
原文地址:http://www.cnblogs.com/lvshijian-1994/p/5190884.html