百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

C#操作数据库原生方法大全

liuian 2025-02-26 12:47 39 浏览

大家好,我是李工。C#编程我们常用操作数据库的ORM有EF、Dapper、SqlSugar、NHibernate这些成熟的框架;但是对于初学者还是推荐原生方法SqlClient,更利于原生SQL、存储过程的编写;有兴趣的小伙伴们可以一起学习。

一、引用SqlClient

using?System.Data.SqlClient;

二、数据库连接字符串

//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.		
public?static?string connectionString?=?ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

三、代码实现

执行简单SQL语句

#region ?执行简单SQL语句


///?
/// 执行SQL语句,返回影响的记录数
///?
///?SQL语句
///?影响的记录数
public static int ExecuteSql(string SQLString)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? using (SqlCommand cmd = new SqlCommand(SQLString, connection))
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Open();
? ? ? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? return rows;
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Close();
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行SQL语句,返回影响的记录数
///?
///?SqlConnection对象
///?SqlTransaction事件
///?SQL语句
///?影响的记录数
public static int ExecuteSql(SqlConnection connection, SqlTransaction trans, string SQLString)
{
? ? using (SqlCommand cmd = new SqlCommand(SQLString, connection))
? ? {
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? cmd.Connection = connection;
? ? ? ? ? ? cmd.Transaction = trans;
? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? return rows;
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? }
}


///?
/// 执行Sql和Oracle滴混合事务
///?
///?SQL命令行列表
///?Oracle命令行列表
///?执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功
public static int ExecuteSqlTran(List?list, List?oracleCmdSqlList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? cmd.Connection = conn;
? ? ? ? SqlTransaction tx = conn.BeginTransaction();
? ? ? ? cmd.Transaction = tx;
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? foreach (CommandInfo myDE in list)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string cmdText = myDE.CommandText;
? ? ? ? ? ? ? ? SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
? ? ? ? ? ? ? ? PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? throw new Exception("违背要求" + myDE.CommandText + "必须符合select count(..的格式");
? ? ? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? ? ? bool isHave = false;
? ? ? ? ? ? ? ? ? ? if (obj == null && obj == DBNull.Value)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? isHave = false;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? isHave = Convert.ToInt32(obj) > 0;
? ? ? ? ? ? ? ? ? ? if (isHave)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? //引发事件
? ? ? ? ? ? ? ? ? ? ? ? myDE.OnSolicitationEvent();
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式");
? ? ? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? ? ? bool isHave = false;
? ? ? ? ? ? ? ? ? ? if (obj == null && obj == DBNull.Value)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? isHave = false;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? isHave = Convert.ToInt32(obj) > 0;


? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0");
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0");
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? int val = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? ? ? ? ? throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? }
? ? ? ? ? ? tx.Commit();
? ? ? ? ? ? return 1;
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? throw e;
? ? ? ? }
? ? ? ? catch (Exception e)
? ? ? ? {
? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? throw e;
? ? ? ? }
? ? }
}


///?
/// 执行多条SQL语句,实现数据库事务。
///?
///?多条SQL语句		
public static int ExecuteSqlTran(List?SQLStringList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? cmd.Connection = conn;
? ? ? ? SqlTransaction tx = conn.BeginTransaction();
? ? ? ? cmd.Transaction = tx;
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? int count = 0;
? ? ? ? ? ? for (int n = 0; n < SQLStringList.Count; n++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string strsql = SQLStringList[n];
? ? ? ? ? ? ? ? if (strsql.Trim().Length > 1)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? cmd.CommandText = strsql;
? ? ? ? ? ? ? ? ? ? count += cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? tx.Commit();
? ? ? ? ? ? return count;
? ? ? ? }
? ? ? ? catch
? ? ? ? {
? ? ? ? ? ? tx.Rollback();
? ? ? ? ? ? return 0;
? ? ? ? }
? ? }
}


///?
/// 执行带一个存储过程参数的的SQL语句。
///?
///?SQL语句
///?参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
///?影响的记录数
public static int ExecuteSql(string SQLString, string content)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? SqlCommand cmd = new SqlCommand(SQLString, connection);
? ? ? ? System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
? ? ? ? myParameter.Value = content;
? ? ? ? cmd.Parameters.Add(myParameter);
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? connection.Open();
? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? return rows;
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? ? ? finally
? ? ? ? {
? ? ? ? ? ? cmd.Dispose();
? ? ? ? ? ? connection.Close();
? ? ? ? }
? ? }
}


///?
/// 执行带一个存储过程参数的的SQL语句。
///?
///?SQL语句
///?参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
///?影响的记录数
public static object ExecuteSqlGet(string SQLString, string content)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? SqlCommand cmd = new SqlCommand(SQLString, connection);
? ? ? ? System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
? ? ? ? myParameter.Value = content;
? ? ? ? cmd.Parameters.Add(myParameter);
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? connection.Open();
? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return obj;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? ? ? finally
? ? ? ? {
? ? ? ? ? ? cmd.Dispose();
? ? ? ? ? ? connection.Close();
? ? ? ? }
? ? }
}


///?
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
///?
///?SQL语句
///?图像字节,数据库的字段类型为image的情况
///?影响的记录数
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? SqlCommand cmd = new SqlCommand(strSQL, connection);
? ? ? ? System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
? ? ? ? myParameter.Value = fs;
? ? ? ? cmd.Parameters.Add(myParameter);
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? connection.Open();
? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? return rows;
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? ? ? finally
? ? ? ? {
? ? ? ? ? ? cmd.Dispose();
? ? ? ? ? ? connection.Close();
? ? ? ? }
? ? }
}


///?
/// 执行一条计算查询结果语句,返回查询结果(object)。
///?
///?计算查询结果语句
///?查询结果(object)
public static object GetSingle(string SQLString)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? using (SqlCommand cmd = new SqlCommand(SQLString, connection))
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Open();
? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return obj;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Close();
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


//执行SQL,设置超时时间
public static object GetSingle(string SQLString, int Times)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? using (SqlCommand cmd = new SqlCommand(SQLString, connection))
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Open();
? ? ? ? ? ? ? ? cmd.CommandTimeout = Times;
? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return obj;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? connection.Close();
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行查询语句,返回SqlDataReader
///?查询语句
///?SqlDataReader
public static SqlDataReader ExecuteReader(string strSQL)
{
? ? SqlConnection connection = new SqlConnection(connectionString);
? ? SqlCommand cmd = new SqlCommand(strSQL, connection);
? ? try
? ? {
? ? ? ? connection.Open();
? ? ? ? SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
? ? ? ? return myReader;
? ? }
? ? catch (System.Data.SqlClient.SqlException e)
? ? {
? ? ? ? throw e;
? ? }


}


///?
/// 执行查询语句,返回DataSet
///?
///?查询语句
///?DataSet
public static DataSet Query(string SQLString)
{


? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? DataSet ds = new DataSet();
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? connection.Open();
? ? ? ? ? ? SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
? ? ? ? ? ? command.Fill(ds, "ds");
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException ex)
? ? ? ? {
? ? ? ? ? ? throw new Exception(ex.Message);
? ? ? ? }
? ? ? ? return ds;
? ? }


}


public static DataSet Query(string SQLString, int Times)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? DataSet ds = new DataSet();
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? connection.Open();
? ? ? ? ? ? SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
? ? ? ? ? ? command.SelectCommand.CommandTimeout = Times;
? ? ? ? ? ? command.Fill(ds, "ds");
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException ex)
? ? ? ? {
? ? ? ? ? ? throw new Exception(ex.Message);
? ? ? ? }
? ? ? ? return ds;
? ? }
}


///?
/// 执行查询语句,返回DataSet
///?
///?SqlConnection对象
///?SqlTransaction事务
///?SQL语句
///?DataSet
public static DataSet Query(SqlConnection connection, SqlTransaction trans, string SQLString)
{
? ? DataSet ds = new DataSet();
? ? try
? ? {
? ? ? ? SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
? ? ? ? command.SelectCommand.Transaction = trans;
? ? ? ? command.Fill(ds, "ds");
? ? }
? ? catch (System.Data.SqlClient.SqlException ex)
? ? {
? ? ? ? throw new Exception(ex.Message);
? ? }
? ? return ds;


}
#endregion

执行带参数的SQL语句

#region 执行带参数的SQL语句


///?
/// 执行SQL语句,返回影响的记录数
///?
///?SQL语句
///?影响的记录数
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? using (SqlCommand cmd = new SqlCommand())
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? PrepareCommand(cmd, connection, null, SQLString, cmdParms);
? ? ? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? return rows;
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行SQL语句,返回影响的记录数
///?
///?SqlConnection对象
///?SqlTransaction对象
///?SQL语句
///?影响的记录数
public static int ExecuteSql(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms)
{
? ? using (SqlCommand cmd = new SqlCommand())
? ? {
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
? ? ? ? ? ? int rows = cmd.ExecuteNonQuery();
? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? return rows;
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? //trans.Rollback();
? ? ? ? ? ? throw e;
? ? ? ? }
? ? }
}


///?
/// 执行多条SQL语句,实现数据库事务。
///?
///?SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? using (SqlTransaction trans = conn.BeginTransaction())
? ? ? ? {
? ? ? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //循环
? ? ? ? ? ? ? ? foreach (DictionaryEntry myDE in SQLStringList)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? string cmdText = myDE.Key.ToString();
? ? ? ? ? ? ? ? ? ? SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
? ? ? ? ? ? ? ? ? ? PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
? ? ? ? ? ? ? ? ? ? int val = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? trans.Commit();
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? throw;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行多条SQL语句,实现数据库事务。
///?
///?SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])
public static int ExecuteSqlTran(System.Collections.Generic.List?cmdList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? using (SqlTransaction trans = conn.BeginTransaction())
? ? ? ? {
? ? ? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? int count = 0;
? ? ? ? ? ? ? ? //循环
? ? ? ? ? ? ? ? foreach (CommandInfo myDE in cmdList)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? string cmdText = myDE.CommandText;
? ? ? ? ? ? ? ? ? ? SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
? ? ? ? ? ? ? ? ? ? PrepareCommand(cmd, conn, trans, cmdText, cmdParms);


? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? ? ? ? ? bool isHave = false;
? ? ? ? ? ? ? ? ? ? ? ? if (obj == null && obj == DBNull.Value)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? isHave = false;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? isHave = Convert.ToInt32(obj) > 0;


? ? ? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? int val = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? ? ? count += val;
? ? ? ? ? ? ? ? ? ? if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? trans.Commit();
? ? ? ? ? ? ? ? return count;
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? throw;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行多条SQL语句,实现数据库事务。
///?
///?SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])
public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List?SQLStringList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? using (SqlTransaction trans = conn.BeginTransaction())
? ? ? ? {
? ? ? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? int indentity = 0;
? ? ? ? ? ? ? ? //循环
? ? ? ? ? ? ? ? foreach (CommandInfo myDE in SQLStringList)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? string cmdText = myDE.CommandText;
? ? ? ? ? ? ? ? ? ? SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
? ? ? ? ? ? ? ? ? ? foreach (SqlParameter q in cmdParms)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? if (q.Direction == ParameterDirection.InputOutput)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? q.Value = indentity;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
? ? ? ? ? ? ? ? ? ? int val = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? ? ? foreach (SqlParameter q in cmdParms)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? if (q.Direction == ParameterDirection.Output)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? indentity = Convert.ToInt32(q.Value);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? trans.Commit();
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? throw;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行多条SQL语句,实现数据库事务。
///?
///?SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
? ? using (SqlConnection conn = new SqlConnection(connectionString))
? ? {
? ? ? ? conn.Open();
? ? ? ? using (SqlTransaction trans = conn.BeginTransaction())
? ? ? ? {
? ? ? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? int indentity = 0;
? ? ? ? ? ? ? ? //循环
? ? ? ? ? ? ? ? foreach (DictionaryEntry myDE in SQLStringList)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? string cmdText = myDE.Key.ToString();
? ? ? ? ? ? ? ? ? ? SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
? ? ? ? ? ? ? ? ? ? foreach (SqlParameter q in cmdParms)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? if (q.Direction == ParameterDirection.InputOutput)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? q.Value = indentity;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
? ? ? ? ? ? ? ? ? ? int val = cmd.ExecuteNonQuery();
? ? ? ? ? ? ? ? ? ? foreach (SqlParameter q in cmdParms)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? if (q.Direction == ParameterDirection.Output)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? indentity = Convert.ToInt32(q.Value);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? trans.Commit();
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? trans.Rollback();
? ? ? ? ? ? ? ? throw;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行一条计算查询结果语句,返回查询结果(object)。
///?
///?计算查询结果语句
///?查询结果(object)
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? using (SqlCommand cmd = new SqlCommand())
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? PrepareCommand(cmd, connection, null, SQLString, cmdParms);
? ? ? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? ? ? if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return obj;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}


///?
/// 执行一条计算查询结果语句,返回查询结果(object)。
///?
///?SqlConnection对象
///?SqlTransaction事务
///?计算查询结果语句
///?查询结果(object)
public static object GetSingle(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms)
{
? ? using (SqlCommand cmd = new SqlCommand())
? ? {
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
? ? ? ? ? ? object obj = cmd.ExecuteScalar();
? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return obj;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException e)
? ? ? ? {
? ? ? ? ? ? //trans.Rollback();
? ? ? ? ? ? throw e;
? ? ? ? }
? ? }
}


///?
/// 执行查询语句,返回SqlDataReader
///?查询语句
///?SqlDataReader
public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
{
? ? SqlConnection connection = new SqlConnection(connectionString);
? ? SqlCommand cmd = new SqlCommand();
? ? try
? ? {
? ? ? ? PrepareCommand(cmd, connection, null, SQLString, cmdParms);
? ? ? ? SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
? ? ? ? cmd.Parameters.Clear();
? ? ? ? return myReader;
? ? }
? ? catch (System.Data.SqlClient.SqlException e)
? ? {
? ? ? ? throw e;
? ? }
}


///?
/// 执行查询语句,返回DataSet
///?
///?查询语句
///?DataSet
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? SqlCommand cmd = new SqlCommand();
? ? ? ? PrepareCommand(cmd, connection, null, SQLString, cmdParms);
? ? ? ? using (SqlDataAdapter da = new SqlDataAdapter(cmd))
? ? ? ? {
? ? ? ? ? ? DataSet ds = new DataSet();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? da.Fill(ds, "ds");
? ? ? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? ? ? }
? ? ? ? ? ? catch (System.Data.SqlClient.SqlException ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? throw new Exception(ex.Message);
? ? ? ? ? ? }
? ? ? ? ? ? return ds;
? ? ? ? }
? ? }
}


///?
/// 执行查询语句,返回DataSet
///?
///?SqlConnection对象
///?SqlTransaction事务
///?查询语句
///?DataSet
public static DataSet Query(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms)
{
? ? SqlCommand cmd = new SqlCommand();
? ? PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
? ? using (SqlDataAdapter da = new SqlDataAdapter(cmd))
? ? {
? ? ? ? DataSet ds = new DataSet();
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? da.Fill(ds, "ds");
? ? ? ? ? ? cmd.Parameters.Clear();
? ? ? ? }
? ? ? ? catch (System.Data.SqlClient.SqlException ex)
? ? ? ? {
? ? ? ? ? ? //trans.Rollback();
? ? ? ? ? ? throw new Exception(ex.Message);
? ? ? ? }
? ? ? ? return ds;
? ? }
}


private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
? ? if (conn.State != ConnectionState.Open)
? ? ? ? conn.Open();
? ? cmd.Connection = conn;
? ? cmd.CommandText = cmdText;
? ? if (trans != null)
? ? ? ? cmd.Transaction = trans;
? ? cmd.CommandType = CommandType.Text;//cmdType;
? ? if (cmdParms != null)
? ? {




? ? ? ? foreach (SqlParameter parameter in cmdParms)
? ? ? ? {
? ? ? ? ? ? if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
? ? ? ? ? ? ? ? (parameter.Value == null))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? parameter.Value = DBNull.Value;
? ? ? ? ? ? }
? ? ? ? ? ? cmd.Parameters.Add(parameter);
? ? ? ? }
? ? }
}


#endregion

存储过程操作

#region 存储过程操作
///?
/// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
///?
///?存储过程名
///?存储过程参数
///?SqlDataReader
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
? ? SqlConnection connection = new SqlConnection(connectionString);
? ? SqlDataReader returnReader;
? ? connection.Open();
? ? SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
? ? command.CommandType = CommandType.StoredProcedure;
? ? returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
? ? return returnReader;
}


///?
/// 执行存储过程
///?
///?存储过程名
///?存储过程参数
///?DataSet结果中的表名
///?DataSet
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? DataSet dataSet = new DataSet();
? ? ? ? connection.Open();
? ? ? ? SqlDataAdapter sqlDA = new SqlDataAdapter();
? ? ? ? sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
? ? ? ? sqlDA.Fill(dataSet, tableName);
? ? ? ? connection.Close();
? ? ? ? return dataSet;
? ? }
}


///?
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
///?
///?数据库连接
///?存储过程名
///?存储过程参数
///?SqlCommand
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
? ? SqlCommand command = new SqlCommand(storedProcName, connection);
? ? command.CommandType = CommandType.StoredProcedure;
? ? foreach (SqlParameter parameter in parameters)
? ? {
? ? ? ? if (parameter != null)
? ? ? ? {
? ? ? ? ? ? // 检查未分配值的输出参数,将其分配以DBNull.Value.
? ? ? ? ? ? if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
? ? ? ? ? ? ? ? (parameter.Value == null))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? parameter.Value = DBNull.Value;
? ? ? ? ? ? }
? ? ? ? ? ? command.Parameters.Add(parameter);
? ? ? ? }
? ? }


? ? return command;
}


///?
/// 执行存储过程,返回影响的行数		
///?
///?存储过程名
///?存储过程参数
///?影响的行数
///?
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
? ? using (SqlConnection connection = new SqlConnection(connectionString))
? ? {
? ? ? ? int result;
? ? ? ? connection.Open();
? ? ? ? SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
? ? ? ? rowsAffected = command.ExecuteNonQuery();
? ? ? ? result = (int)command.Parameters["ReturnValue"].Value;
? ? ? ? //Connection.Close();
? ? ? ? return result;
? ? }
}


///?
/// 创建 SqlCommand 对象实例(用来返回一个整数值)	
///?
///?存储过程名
///?存储过程参数
///?SqlCommand 对象实例
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
? ? SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
? ? command.Parameters.Add(new SqlParameter("ReturnValue",
? ? ? ? SqlDbType.Int, 4, ParameterDirection.ReturnValue,
? ? ? ? false, 0, 0, string.Empty, DataRowVersion.Default, null));
? ? return command;
}
#endregion

以上就实现了对数据的所有操作,快去试试吧。

相关推荐

2023年最新微信小程序抓包教程(微信小程序 抓包)

声明:本公众号大部分文章来自作者日常学习笔记,部分文章经作者授权及其他公众号白名单转载。未经授权严禁转载。如需转载,请联系开百。请不要利用文章中的相关技术从事非法测试。由此产生的任何不良后果与文...

测试人员必看的软件测试面试文档(软件测试面试怎么说)

前言又到了毕业季,我们将会迎来许多需要面试的小伙伴,在这里呢笔者给从事软件测试的小伙伴准备了一份顶级的面试文档。1、什么是bug?bug由哪些字段(要素)组成?1)将在电脑系统或程序中,隐藏着的...

复活,视频号一键下载,有手就会,长期更新(2023-12-21)

视频号下载的话题,也算是流量密码了。但也是比较麻烦的问题,频频失效不说,使用方法也难以入手。今天,奶酪就来讲讲视频号下载的新方案,更关键的是,它们有手就会有用,最后一个方法万能。实测2023-12-...

新款HTTP代理抓包工具Proxyman(界面美观、功能强大)

不论是普通的前后端开发人员,还是做爬虫、逆向的爬虫工程师和安全逆向工程,必不可少会使用的一种工具就是HTTP抓包工具。说到抓包工具,脱口而出的肯定是浏览器F12开发者调试界面、Charles(青花瓷)...

使用Charles工具对手机进行HTTPS抓包

本次用到的工具:Charles、雷电模拟器。比较常用的抓包工具有fiddler和Charles,今天讲Charles如何对手机端的HTTS包进行抓包。fiddler抓包工具不做讲解,网上有很多fidd...

苹果手机下载 TikTok 旧版本安装包教程

目前苹果手机能在国内免拔卡使用的TikTok版本只有21.1.0版本,而AppStore是高于21.1.0版本,本次教程就是解决如何下载TikTok旧版本安装包。前期准备准备美区...

【0基础学爬虫】爬虫基础之抓包工具的使用

大数据时代,各行各业对数据采集的需求日益增多,网络爬虫的运用也更为广泛,越来越多的人开始学习网络爬虫这项技术,K哥爬虫此前已经推出不少爬虫进阶、逆向相关文章,为实现从易到难全方位覆盖,特设【0基础学爬...

防止应用调试分析IP被扫描加固实战教程

防止应用调试分析IP被扫描加固实战教程一、概述在当今数字化时代,应用程序的安全性已成为开发者关注的焦点。特别是在应用调试过程中,保护应用的网络安全显得尤为重要。为了防止应用调试过程中IP被扫描和潜在的...

一文了解 Telerik Test Studio 测试神器

1.简介TelerikTestStudio(以下称TestStudio)是一个易于使用的自动化测试工具,可用于Web、WPF应用的界面功能测试,也可以用于API测试,以及负载和性能测试。Te...

HLS实战之Wireshark抓包分析(wireshark抓包总结)

0.引言Wireshark(前称Ethereal)是一个网络封包分析软件。网络封包分析软件的功能是撷取网络封包,并尽可能显示出最为详细的网络封包资料。Wireshark使用WinPCAP作为接口,直接...

信息安全之HTTPS协议详解(加密方式、证书原理、中间人攻击 )

HTTPS协议详解(加密方式、证书原理、中间人攻击)HTTPS协议的加密方式有哪些?HTTPS证书的原理是什么?如何防止中间人攻击?一:HTTPS基本介绍:1.HTTPS是什么:HTTPS也是一个...

Fiddler 怎么抓取手机APP:抖音、小程序、小红书数据接口

使用Fiddler抓取移动应用程序(APP)的数据接口需要进行以下步骤:首先,确保手机与计算机连接在同一网络下。在计算机上安装Fiddler工具,并打开它。将手机的代理设置为Fiddler代理。具体方...

python爬虫教程:教你通过 Fiddler 进行手机抓包

今天要说说怎么在我们的手机抓包有时候我们想对请求的数据或者响应的数据进行篡改怎么做呢?我们经常在用的手机手机里面的数据怎么对它抓包呢?那么...接下来就是学习python的正确姿势我们要用到一款强...

Fiddler入门教程全家桶,建议收藏

学习Fiddler工具之前,我们先了解一下Fiddler工具的特点,Fiddler能做什么?如何使用Fidder捕获数据包、修改请求、模拟客户端向服务端发送请求、实施越权的安全性测试等相关知识。本章节...

fiddler如何抓取https请求实现手机抓包(100%成功解决)

一、HTTP协议和HTTPS协议。(1)HTTPS协议=HTTP协议+SSL协议,默认端口:443(2)HTTP协议(HyperTextTransferProtocol):超文本传输协议。默认...