SqlHelper
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 ADONET2 10 { 11 class SqlHelper 12 { 13 private static string connStr = ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString; 14 15 public static int ExecuteNonQuery(string sql) 16 { 17 using (SqlConnection conn = new SqlConnection(connStr)) 18 { 19 conn.Open(); 20 using (SqlCommand cmd = conn.CreateCommand()) 21 { 22 cmd.CommandText = sql; 23 return cmd.ExecuteNonQuery();//返回值代表影响了多少行数据 24 } 25 } 26 } 27 28 public static object ExecuteScalar(string sql) 29 { 30 using (SqlConnection conn = new SqlConnection(connStr)) 31 { 32 conn.Open(); 33 using (SqlCommand cmd = new SqlCommand()) 34 { 35 cmd.CommandText = sql; 36 return cmd.ExecuteScalar(); 37 } 38 } 39 } 40 41 public static DataSet ExecuteDataSet(string sql) 42 { 43 using (SqlConnection conn = new SqlConnection(connStr)) 44 { 45 conn.Open(); 46 using (SqlCommand cmd = new SqlCommand(sql,conn)) 47 { 48 //cmd.Connection = conn; /*不知道为什么必须要设置这个 49 //cmd.CommandText = sql; 50 SqlDataAdapter adapter = new SqlDataAdapter(cmd); 51 DataSet dataset = new DataSet(); 52 adapter.Fill(dataset); 53 return dataset; 54 } 55 } 56 } 57 } 58 }
1 //SqlHelper的使用 2 3 DataSet ds = SqlHelper.ExecuteDataSet("select * from T_Student"); 4 foreach (DataRow row in ds.Tables[0].Rows) 5 { 6 string name = (string)row["Name"]; 7 int age = (int)row["Age"]; 8 MessageBox.Show(name + "," + age); 9 }
我是一个小小虫
用编程改变世界