标签:
为了更快捷的反问数据库,以及更加符合面向对象封装的原则,我们应该有一个自己的数据库操作类,SqlHelper.cs 这样我们在访问数据库的时候就不必每一次都连接、赋值、执行了,可以比较方便的一步到位。
private static string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
public static int ExecuteNonQuery(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; return cmd.ExecuteNonQuery(); } } }
public static object ExecuteScalar(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; return cmd.ExecuteScalar(); } } }
public static DataTable ExecuteDataTable(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DataTable dt = ds.Tables[0]; return dt; } } }
private void button2_Click(object sender, RoutedEventArgs e) { DataTable dt = SqlHelper.ExecuteDataTable("select * from Student"); foreach (DataRow dr in dt.Rows) { string name = (string)dr[0]; MessageBox.Show(name); } }
public static int ExecuteNonQuery(string sql,params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } public static object ExecuteScalar(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteScalar(); } } } public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset); return dataset.Tables[0]; } } }
private void button3_Click(object sender, RoutedEventArgs e) { DataTable dt = SqlHelper.ExecuteDataTable("select * from Student where name = @name",new SqlParameter("@name","xuweixi")); foreach (DataRow dr in dt.Rows) { string name = (string)dr[0]; MessageBox.Show(name); } }
(5)C#之ADO.NET 手写SqlHelp.cs 以及改进
标签:
原文地址:http://www.cnblogs.com/kaolalovemiaomiao/p/4707564.html