求一段操作数据(增删改查)的代码
求一段操作数据的代码
要求是通用的,不管字段多少,数据类型、长度,单表的即可
------解决方案--------------------增:Insert into tablename values(...)
刪:Delete from Tablename where(...)
改:Update Tablename Set(...) where(...)
保証通用
------解决方案--------------------public class Connection {
private string connStr;
private SqlTransaction tran;
public SqlConnection conn;
private SqlCommand cmd;
public Connection() {
connStr = ConfigurationSettings.AppSettings[ "ConnStr "];
conn = new SqlConnection(connStr);
}
/// <summary>
/// 打开数据库连接
/// </summary>
public void Open() {
if(conn!=null) {
conn.Close();
}
conn.Open();
}
/// <summary>
/// 关闭数据库连接
/// </summary>
public void Close() {
if(conn!=null) {
conn.Close();
}
}
/// <summary>
/// 开始事务
/// </summary>
public void TranBegin() {
Open();
tran = conn.BeginTransaction();
}
/// <summary>
/// 回滚事务
/// </summary>
public void TranRollback(){
tran.Rollback();
if (conn != null) {
conn.Dispose(); // 关闭数据库
conn.Close(); // 关系数据库
}
}
/// <summary>
/// 回滚事务到指定点
/// </summary>
/// <param name= "tranName "> 指定点 </param>
public void TranRollback(string tranName){
tran.Rollback(tranName);
if (conn != null) {
conn.Dispose(); // 关闭数据库
conn.Close(); // 关系数据库
}
}
/// <summary>
/// 结束事务
/// </summary>
public void TranEnd() {
tran.Commit(); // 结束事务
if (conn != null) {
conn.Dispose(); // 关闭数据库
conn.Close(); // 关系数据库
}
}
/// <summary>
/// 根据SQL语句返回包含结果集的数据表
/// </summary>
/// <param name= "sql "> SELECT类型的SQL语句 </param>
/// <returns> 返回数据表 </returns>
public DataTable GetDataTable(string sql) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
cmd.Transaction = tran;
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
/// <summary>
/// 根据SQL语句返回包含结果集的数据表
/// </summary>
/// <param name= "cmd "> 命令对象 </param>
/// <returns> 返回数据表 </returns>
public DataTable GetDataTable(SqlCommand cmd) {
cmd.Connection = conn;
cmd.Transaction = tran;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
/// <summary>
/// 执行UPDATE,DELETE,INSERT类型的SQL语句
/// </summary>
/// <param name= "sql "> SQL语句 </param>
/// <returns> 返回受影响的行数 </returns>
public int update(string sql) {
int rs = 0;
cmd=new SqlCommand(sql,conn);
cmd.Transaction = tran;
rs = cmd.ExecuteNonQuery();
return rs;
}
/// <summary>
/// 执行UPDATE,DELETE,INSERT类型的SQL语句
/// </summary>
/// <param name= "sql "> 命令对象 </param>
/// <returns> 返回受影响的行数 </returns>