日期:2014-05-16 浏览次数:20403 次
话不多少 直接贴代码
?
需引入的命名空间
?
定义连接属性
1 private SqlConnection conn; 2 public SqlConnection Conn 3 { 4 get 5 { 6 if (conn == null) 7 { 8 string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; 9 conn = new SqlConnection(connStr); 10 } 11 if (conn.State == ConnectionState.Closed) 12 conn.Open(); 13 if (conn.State == ConnectionState.Broken) 14 { 15 conn.Close(); 16 conn.Open(); 17 } 18 return conn; 19 } 20 }
做查询(包括sql语句和带参数的SQL语句)
1 //查询:DataReader 2 public SqlDataReader GetReader(string sql) 3 { 4 SqlCommand cmd = new SqlCommand(sql, Conn); 5 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 6 } 7 public SqlDataReader GetReader(string sql,SqlParameter[] paras) 8 { 9 SqlCommand cmd = new SqlCommand(sql, Conn); 10 cmd.Parameters.AddRange(paras); 11