首页 > 代码库 > 自学.net(1)手写一个sqlhelper类

自学.net(1)手写一个sqlhelper类

自学.net已经快一个月了,看的是传智播客的视频,今天正好申请了博客,就先把手写的sqlhelper类上传上去吧

别忘了在解决方案管理器的“引用”添加System.Configuration   

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Configuration; 6 using System.Data.SqlClient; 7 using System.Data; 8  9 namespace SH10 {11     class SqlHelper12     {13         private static string connStr = ConfigurationManager.ConnectionStrings["dbConnStr"]
        .ConnectionString;
14 15 16 public static int ExecuteNonQuery(string sql,params SqlParameter[] parameters)17 {18 using (SqlConnection conn = new SqlConnection(connStr))19 {20 conn.Open();21 using (SqlCommand cmd = conn.CreateCommand())22 {23 cmd.CommandText = sql;24 //foreach (SqlParameter param in parameters)25 //{26 // cmd.Parameters.Add(param);27 //}28 cmd.Parameters.AddRange(parameters);29 return cmd.ExecuteNonQuery();30 }31 }32 }33 34 public static object ExecuteScalar(string sql, params SqlParameter[] parameters)35 {36 using (SqlConnection conn = new SqlConnection(connStr))37 {38 conn.Open();39 using (SqlCommand cmd = conn.CreateCommand())40 {41 cmd.CommandText = sql;42 cmd.Parameters.AddRange(parameters);43 return cmd.ExecuteScalar();44 }45 }46 }47 48 //只用来执行查询结果比较少的sql49 public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)50 {51 using (SqlConnection conn = new SqlConnection(connStr))52 {53 conn.Open();54 using (SqlCommand cmd = conn.CreateCommand())55 {56 cmd.CommandText = sql;57 cmd.Parameters.AddRange(parameters);58 59 SqlDataAdapter adapter = new SqlDataAdapter(cmd);60 DataSet dataset = new DataSet();61 adapter.Fill(dataset);62 return dataset.Tables[0];63 }64 }65 }66 }67 }

 

自学.net(1)手写一个sqlhelper类