标签:
一:ADO.NET实现三层架构
不用三层的普通的查询写法:
string sql = string.Format("select * from Studnet where StuName like ‘%{0}%‘", txtName.Text); string strconn = "server=.;database=MySc;uid=sa;pwd=123456"; SqlConnection conn = new SqlConnection(strconn); SqlDataAdapter da = new SqlDataAdapter("select * fromStuden", conn); DataSet ds = new DataSet(); try { da.Fill(ds); // dataGridView1.DataSource = ds.Tables[0]; DataTable dt = ds.Tables[0]; txtName.Text = dt.Rows[0]["Name"].ToString(); } catch (Exception) { throw; }
普通删除的写法:
SqlConnection conn = new SqlConnection("server=.;database=MySc;uid=sa;pwd=123456"); string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); string sql = "delect from Student where stNO=" + id; SqlCommand comm = new SqlCommand(sql,conn); conn.Open();
修改的普通写法:
string strsql = @"UPDATE Student SET [StuName]=‘0‘ WHERE [StuNO]={3}"; string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); string sql = string.Format(strsql, txtName.Text, id); SqlConnection conn = new SqlConnection("server=.;database=MySc;uid=sa;pwd=123456"); SqlCommand com = new SqlCommand(sql, conn); try { conn.Open(); com.ExecuteNonQuery(); //刷新数据 } catch (Exception) { throw; } finally { conn.Close(); }
一个简单的DbHelper:
private static SqlConnection conn = new SqlConnection("server=.;database=Mys,uid=sa;pwd=123456"); public static int ExecuteSQL(string strsql) { SqlCommand comm = new SqlCommand(strsql, conn); try { conn.Open(); return comm.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { conn.Close(); } } public static int GetDataTable(string strsql) { SqlDataAdapter da = new SqlDataAdapter(strsql, conn); DataSet ds = new DataSet(); try { da.Fill(ds); return ds.Tables[0]; } catch (Exception ex) { throw ex; } } /// <summary> /// 返回一个单一的值 /// </summary> /// <param name="strsql">传入的是select打头的sql语句(select count(*),select max(..))</param> /// <returns>返回的是Object类型</returns> public static object GetSingle(string strsql) { SqlCommand comm = new SqlCommand(strsql, conn); try { conn.Open; return comm.ExecuteScalar(); } catch (Exception ex) { throw ex; } finally { conn.Close(); } }
二:用OOP实现三层架构
三:应用抽象工厂+反射实现通用数据源的设计
标签:
原文地址:http://www.cnblogs.com/sunliyuan/p/5797564.html