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

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

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

大家好,我是李工。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

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

相关推荐

python入门到脱坑函数—定义函数_如何定义函数python

Python函数定义:从入门到精通一、函数的基本概念函数是组织好的、可重复使用的代码块,用于执行特定任务。在Python中,函数可以提高代码的模块性和重复利用率。二、定义函数的基本语法def函数名(...

javascript函数的call、apply和bind的原理及作用详解

javascript函数的call、apply和bind本质是用来实现继承的,专业点说法就是改变函数体内部this的指向,当一个对象没有某个功能时,就可以用这3个来从有相关功能的对象里借用过来...

JS中 call()、apply()、bind() 的用法

其实是一个很简单的东西,认真看十分钟就从一脸懵B到完全理解!先看明白下面:例1obj.objAge;//17obj.myFun()//小张年龄undefined例2shows(...

Pandas每日函数学习之apply函数_apply函数python

apply函数是Pandas中的一个非常强大的工具,它允许你对DataFrame或Series中的数据应用一个函数,可以是自定义的函数,也可以是内置的函数。apply可以作用于DataF...

Win10搜索不习惯 换个设定就好了_window10搜索用不了怎么办

Windows10的搜索功能是真的方便,这点用惯了Windows10的小伙伴应该都知道,不过它有个小问题,就是Windows10虽然会自动联网搜索,但默认使用微软自家的Bing搜索引擎和Edge...

面试秘籍:call、bind、apply的区别,面试官为什么总爱问这三位?

引言你有没有发现,每次JavaScript面试,面试官总爱问你call、bind和apply的区别?好像这三个方法成了通关密码,掌握了它们,就能顺利过关。其实不难理解,面试官问这些问题,不...

记住这8招,帮你掌握“追拍“摄影技法—摄影早自习第422日

杨海英同学提问:请问叶梓老师,我练习追拍时,总也不能把运动的人物拍清晰,速度一般掌握在1/40-1/60,请问您如何把追拍拍的清晰?这跟不同的运动形式有关系吗?请您给讲讲要点,谢谢您!摄影:Damia...

[Sony] 有点残酷的测试A7RII PK FS7

都是好机!手中利器!主要是最近天天研究fs5,想知道fs5与a7rii后期匹配问题,苦等朋友的fs5月底到货,于是先拿手里现有的fs7小测一下,十九八九也能看到fs5的影子,另外也了解一下fs5k标配...

AndroidStudio_Android使用OkHttp发起Http请求

这个okHttp的使用,其实网络上有很多的案例的,但是,如果以前没用过,copy别人的直接用的话,可以发现要么导包导不进来,要么,人家给的代码也不完整,这里自己整理一下.1.引入OkHttp的jar...

ESL-通过事件控制FreeSWITCH_es事务控制

通过事件提供的最底层控制机制,允许我们有效地利用工具箱,适时选择使用其中的单个工具。FreeSWITCH是一个核心交换与混合矩阵,它周围有几十个模块提供各种功能特性。我们完全控制了所有的即时信息,这些...

【调试】perf和火焰图_perf生成火焰图

简介perf是linux上的性能分析工具,perf可以对event进行统计得到event的发生次数,或者对event进行采样,得到每次event发生时的相关数据(cpu、进程id、运行栈等),利用这些...

文本检索控件也玩安卓?dtSearch Engine发布Android测试版

dtSearchEngineforLinux(原生64-bit/32-bitC++和JavaAPIs)和dtSearchEngineforWin&.NET(原生64-bi...

网站后台莫名增加N个管理员,记一次SQL注入攻击

网站没流量,但却经常被SQL注入光顾。最近,网站真的很奇怪,网站后台不光莫名多了很多“管理员”,所有的Wordpres插件还会被自动暂停,导致一些插件支持的页面,如WooCommerce无法正常访问、...

多元回归树分析Multivariate Regression Trees,MRT

多元回归树(MultivariateRegressionTrees,MRT)是单元回归树的拓展,是一种对一系列连续型变量递归划分成多个类群的聚类方法,是在决策树(decision-trees)基础...

JMETER性能测试_JMETER性能测试指标

jmeter为性能测试提供了一下特色:jmeter可以对测试静态资源(例如js、html等)以及动态资源(例如php、jsp、ajax等等)进行性能测试jmeter可以挖掘出系统最大能处...