设为首页 收藏本站
查看: 510|回复: 0

[经验分享] ASP.NET C# 调用存储过程 SQL SERVER 事务 数据库操作类

[复制链接]

尚未签到

发表于 2016-11-7 09:22:24 | 显示全部楼层 |阅读模式
  我们现在写一个SQL SERVER的数据库简单的操作类。
  包括事务,存储过程调用。
  类文件如下:
  using System;using System.Collections.Generic;using System.Text;using System.Data.SqlClient;using System.Data;namespace DALFactory{public class DBLib{private SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["connstr"]);//private SqlConnection con = new SqlConnection("Server=SUNLEI;DataBase=WEB;UID=sa;PWD=123456");//全局事务private SqlTransaction Tx = null;public DBLib(){}//手动开始事务public void BeginTransaction(){con.Open();Tx = con.BeginTransaction();}//手动提交事务public void CommitTransaction(){Tx.Commit();con.Close();Tx = null;}//手动回滚事务public void RollbackTransaction(){try{Tx.Rollback();con.Close();Tx = null;}catch{}}public void CloseConnetion(){try{if(con.State!=ConnectionState.Closed)con.Close();}catch{}}//给存储过程的参数赋值public SqlCommand SetParams(SqlTypeBean[] bean, String ProcedureName){if (bean == null)bean = new SqlTypeBean[] { };SqlCommand cmd = new SqlCommand();cmd.Connection = con;cmd.CommandType = System.Data.CommandType.StoredProcedure;cmd.CommandText = ProcedureName;String para = "";for (int i = 0; i < bean.Length; i++){para = para + bean.GetName() + "=" + bean.GetValueString();SqlParameter param = null;if (object.Equals(bean.GetClumType(), SqlDbType.VarChar)){param = new SqlParameter(bean.GetName(), SqlDbType.VarChar, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Int)){param = new SqlParameter(bean.GetName(), SqlDbType.Int, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueLong();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.DateTime)){param = new SqlParameter(bean.GetName(), SqlDbType.DateTime, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = DateTime.Parse(bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Char)){param = new SqlParameter(bean.GetName(), SqlDbType.Char, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = char.Parse(bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Bit)){param = new SqlParameter(bean.GetName(), SqlDbType.Bit, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Decimal)){param = new SqlParameter(bean.GetName(), SqlDbType.Decimal, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueDouble();cmd.Parameters.Add(param);continue;}}Log.WriteLog("执行存储过程为:" + ProcedureName + "\n参数为:"+para);if (cmd.Connection.State != ConnectionState.Open)cmd.Connection.Open();return cmd;}//给绑定变量的参数赋值public SqlCommand SetParamsSql(SqlTypeBean[] Bean, String Sql){SqlCommand cmd = new SqlCommand(Sql);cmd.Connection = con;if (Bean == null)Bean = new SqlTypeBean[] { };String para = "";for (int i = 0; i < Bean.Length; i++){para = para + Bean.GetName() + "=" + Bean.GetValueString();SqlParameter param = null;if (object.Equals(Bean.GetClumType(), SqlDbType.VarChar)){param = new SqlParameter(Bean.GetName(), SqlDbType.VarChar, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Int)){param = new SqlParameter(Bean.GetName(), SqlDbType.Int, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueLong();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.DateTime)){param = new SqlParameter(Bean.GetName(), SqlDbType.DateTime, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = DateTime.Parse(Bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Char)){param = new SqlParameter(Bean.GetName(), SqlDbType.Char, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = char.Parse(Bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Bit)){param = new SqlParameter(Bean.GetName(), SqlDbType.Bit, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Decimal)){param = new SqlParameter(Bean.GetName(), SqlDbType.Decimal, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueDouble();cmd.Parameters.Add(param);continue;}}Log.WriteLog("执行存储过程为:" + Sql + "\n参数为:" + para);if (cmd.Connection.State!=ConnectionState.Open)cmd.Connection.Open();return cmd;}//给存储过程的参数赋值,这方法需要在事务中使用public SqlCommand SetParamsTransactionProce(SqlTypeBean[] bean, String ProcedureName){if (bean == null)bean = new SqlTypeBean[] { };SqlCommand cmd = new SqlCommand();cmd.Connection = con;cmd.Transaction = Tx;cmd.CommandType = System.Data.CommandType.StoredProcedure;cmd.CommandText = ProcedureName;String para = "";for (int i = 0; i < bean.Length; i++){para = para + bean.GetName() + "=" + bean.GetValueString();SqlParameter param = null;if (object.Equals(bean.GetClumType(), SqlDbType.VarChar)){param = new SqlParameter(bean.GetName(), SqlDbType.VarChar, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Int)){param = new SqlParameter(bean.GetName(), SqlDbType.Int, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueLong();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.DateTime)){param = new SqlParameter(bean.GetName(), SqlDbType.DateTime, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = DateTime.Parse(bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Char)){param = new SqlParameter(bean.GetName(), SqlDbType.Char, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = char.Parse(bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Bit)){param = new SqlParameter(bean.GetName(), SqlDbType.Bit, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(bean.GetClumType(), SqlDbType.Decimal)){param = new SqlParameter(bean.GetName(), SqlDbType.Decimal, bean.GetClumLength());if (bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = bean.GetValueDouble();cmd.Parameters.Add(param);continue;}}Log.WriteLog("执行存储过程为:" + ProcedureName + "\n参数为:" + para);return cmd;}//给绑定变量赋值,此方法需要事务控制public SqlCommand SetParamsTransactionSql(SqlTypeBean[] Bean, String Sql){if (Bean == null)Bean = new SqlTypeBean[] { };SqlCommand cmd = new SqlCommand(Sql);cmd.Connection = con;cmd.Transaction = Tx;String para = "";for (int i = 0; i < Bean.Length; i++){para = para + Bean.GetName() + "=" + Bean.GetValueString();SqlParameter param = null;if (object.Equals(Bean.GetClumType(), SqlDbType.VarChar)){param = new SqlParameter(Bean.GetName(), SqlDbType.VarChar, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Int)){param = new SqlParameter(Bean.GetName(), SqlDbType.Int, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueLong();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.DateTime)){param = new SqlParameter(Bean.GetName(), SqlDbType.DateTime, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = DateTime.Parse(Bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Char)){param = new SqlParameter(Bean.GetName(), SqlDbType.Char, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = char.Parse(Bean.GetValueString());cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Bit)){param = new SqlParameter(Bean.GetName(), SqlDbType.Bit, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueString();cmd.Parameters.Add(param);continue;}else if (object.Equals(Bean.GetClumType(), SqlDbType.Decimal)){param = new SqlParameter(Bean.GetName(), SqlDbType.Decimal, Bean.GetClumLength());if (Bean.GetIsOutPut()){param.Direction = ParameterDirection.Output;}param.Value = Bean.GetValueDouble();cmd.Parameters.Add(param);continue;}}Log.WriteLog("执行存储过程为:" + Sql + "\n参数为:" + para);return cmd;}//执行readerpublic SqlDataReader GetReader(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsSql(Bean, Sql);return command.ExecuteReader();}//执行reader,需要在事务中使用。public SqlDataReader GetTransactionReader(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsTransactionSql(Bean, Sql);return command.ExecuteReader();}//执行普通的sqlpublic bool ExecSql(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsSql(Bean, Sql);command.ExecuteNonQuery();command.Connection.Close();return true;}//执行事务控制的sqlpublic bool ExecTransactionSql(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsTransactionSql(Bean, Sql);command.ExecuteNonQuery();return true;}//取得记录的第一行第一列的值public String GetTransactionOneString(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsTransactionSql(Bean, Sql);String result = command.ExecuteScalar().ToString();return result;}//取得记录的第一行第一列的值public String GetOneString(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsSql(Bean, Sql);String result = command.ExecuteScalar().ToString();command.Connection.Close();command.Dispose();return result;}//// Summary://     Initializes a new instance of the System.Data.SqlClient.SqlCommand class//     with the text of the query and a System.Data.SqlClient.SqlConnection.//// Parameters://   Sql://     The text of the query.////   Bean://     A System.Data.SqlClient.SqlConnection that represents the connection to an//     instance of SQL Server.public DataSet GetDataSet(String Sql, SqlTypeBean[] Bean){SqlCommand command = SetParamsSql(Bean, Sql);//command.Connection.Open();SqlDataAdapter SqlAdapter = new SqlDataAdapter(command);DataSet ds = new DataSet();SqlAdapter.Fill(ds);return ds;}}}
  上面这个类包括常用的操作数据库的方法,下面我们来写几个test用例
  public class UnitTest1
{
public UnitTest1()
{
//
// TODO: Add constructor logic here
//
}
  [TestMethod]
  //这里演示怎么调用事务,用绑定变量。
public void TestMethod1()
{
DBLib lib = new DBLib();
try
{
lib.BeginTransaction();//要使用事务,这里必须要先BeginTransaction(),下面执行的方法都要调用带Transaction的方法。
String sql = "INSERT INTO testtable VALUES(@tid,@text)";
SqlTypeBean[] bean = new SqlTypeBean[2];
bean[0] = new SqlTypeBean(false, "@tid", "18", 4, SqlDbType.Int);
bean[1] = new SqlTypeBean(false, "@text", "good", 50, SqlDbType.VarChar);
lib.ExecTransactionSql(sql, bean);
System.Console.WriteLine("ok!");
sql = "INSERT INTO testtable VALUES(@tid,@text)";
  bean[0] = new SqlTypeBean(false, "@tid", "17", 4, SqlDbType.Int);
bean[1] = new SqlTypeBean(false, "@text", "good", 50, SqlDbType.VarChar);
lib.ExecTransactionSql(sql, bean);
System.Console.WriteLine("ok!");
  lib.CommitTransaction();
}
catch (Exception e)
{
lib.RollbackTransaction();
throw e;
}
}
[TestMethod]
  //这里普通的调用
public void TestMethod2()
{
DBLib lib = new DBLib();
String sql = "INSERT INTO testtable VALUES(@tid,@text)";
SqlTypeBean[] bean = new SqlTypeBean[2];
bean[0] = new SqlTypeBean(false, "@tid", "7", 4, SqlDbType.Int);
bean[1] = new SqlTypeBean(false, "@text", "good", 50, SqlDbType.VarChar);
lib.ExecSql(sql, bean);
}
  [TestMethod]
  //这里是带返回值的存储
public void TestMethod3()
{
DBLib lib = new DBLib();
SqlTypeBean[] bean = new SqlTypeBean[2];
bean[0] = new SqlTypeBean(true, "@COUNT", "7", 4, SqlDbType.Int);
bean[1] = new SqlTypeBean(false, "@TEXT", "good", 50, SqlDbType.VarChar);
SqlCommand cmd = lib.SetParams(bean,"GETCOUNT");
cmd.ExecuteNonQuery();
String result = cmd.Parameters["@COUNT"].Value.ToString();
String result1 = cmd.Parameters["@COUNT"].Value.ToString();
cmd.Connection.Close();
}
}

  存储存储过程变量的bean
  using System;
using System.Collections.Generic;
using System.Text;
  namespace SpLib.db
{
//本类用于存放变量类型
public class SqlTypeBean
{
//这里设定变量是输入变量还是输出变量。默认是输入变量
private bool IsOutPut = false;
//这里存放字段变量的名称
private String Name;
//这里存放字段变量的值
private String Value;
//这里存放字段的长度
private int ClumLength;
//这里存放字段的类型
private object ClumType;

  public SqlTypeBean(bool IsOutPut, String Name, String Value, int ClumLength, object ClumType)
{
this.IsOutPut = IsOutPut;
this.Name = Name;
this.Value = Value;
this.ClumLength = ClumLength;
this.ClumType = ClumType;

}
  public SqlTypeBean( String Name, String Value, int ClumLength, object ClumType)
{
this.IsOutPut = false;
this.Name = Name;
this.Value = Value;
this.ClumLength = ClumLength;
this.ClumType = ClumType;
  }
  public bool GetIsOutPut()
{
return IsOutPut;
}
  public String GetName()
{
return Name;
}
  public object GetClumType()
{
return ClumType;
}
  public String GetValueString()
{
return Value;
}
  public long GetValueLong()
{
return long.Parse(Value);
}
  public bool GetValueBool()
{
return bool.Parse(Value);
}
  public int GetClumLength()
{
return ClumLength;
}
  }
}
  原创文章,转载请标明出处http://blog.csdn.net/keyboardsun
  作者 keyboardsun

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-296852-1-1.html 上篇帖子: 学习SQL SERVER的存储过程-之一认识存储过程语法 下篇帖子: SQL Server数据库查询速度慢原因及优化方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表