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

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

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

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

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

相关推荐

eset nod32 24位激活码(eset激活码生成器)

ESETNOD32Antivirus4的激活码是24位的例如M26D-0233-4W9Q-VSSB-D84G-JJJJ或V26D-0243-4W9Q-VSSB-D84G-JGFD(友情提示...

鸿蒙系统的优缺点(鸿蒙4.3和5.0哪个好)

一、鸿蒙系统的缺点鸿蒙最大的缺点应该就是生态了。鸿蒙系统依赖安卓生态无可厚非,前者毕竟是一款刚刚发布两年的新系统。而安卓,早在几十年前就已经上线,谷歌建设安卓生态也用了十多年的时间。在巨大的时间差面前...

bios怎么格式化c盘(bios格式下怎么彻底格式化电脑)
bios怎么格式化c盘(bios格式下怎么彻底格式化电脑)

步骤/方式1BIOS没有格式化硬盘的功能。对硬盘进行格式化,首先需要给硬盘分区并分配文件系统,BIOS不支持文件系统的识别,所以也不支持格式化的功能。步骤/方式2早期的计算机系统在BIOS里面曾经有过低级格式化的功能,但是低级格式化只是对硬...

2025-12-22 20:05 liuian

电脑开机显示屏显示蓝屏(开机后显示器蓝屏)

造成电脑蓝屏的原因主要有以下几点。1、电脑使用过度,温度过高过度使用电脑会导致电脑硬件发生损坏,系统超载,内部运算过多,cpu温度急剧升高,会发生系统错误。建议更换散热系统,更新“小风扇”设备,并合...

设置无线网密码步骤(如何设置无线网络wifi密码)

首先使用已经连接到网络的手机或电脑,在浏览器地址栏输入192.168.1.1或者192.168.0.1;输入管理员账号和密码,两个一般都是输入admin;点击【无线设置】,进入【安全选项】,在输入旧密...

下载优酷官方正版(下载优酷官方正版网站)

您好,直接打开浏览器或者打开手机的应用商城,然后输入该软件的名称然后搜索即可在搜索结果中下载安装即可,也可以下载一个市场类软件,常见的有安卓市场,机锋市场等,之后使用此款软件下载其他程序。优酷视频...

iso文件安装器(iso安装程序)

不能。苹果手机是不能安装apk格式软件的,apk是安卓系统的安装包格式。通过将APK文件直接传到Android模拟器或Android手机中执行即可安装。apk文件和sis一样,把androidsdk...

台式电脑重装系统按哪个键进入
台式电脑重装系统按哪个键进入

不同品牌的设备按键是不同的1、如果原来电脑装一键还原软件,装系统时直接在启动画面选择重新恢复系统项即可;2、如需启动光盘或者优盘来重装系统,需要开机按启动热键,选择对应的按键即可调出启动菜单选择界面,在菜单中选择优盘或光驱,按回车,按提示进...

2025-12-22 17:55 liuian

戴尔笔记本电脑一开机就蓝屏

笔记本蓝屏可能是电脑硬盘故障,可以更换一个硬盘尝试。也可能是更新了驱动与修复漏洞补丁,可以进入安全模式将更新的驱动删除。有可能是内存条故障,可以把内存条取下来,用橡皮擦轻轻擦拭金手指,然后用毛刷将内存...

优酷路由宝怎么设置(优酷路由宝怎么设置网络)

无线连接如果准备用手机、笔记本电脑来设置优酷路由宝,需要先把WAN口,连接宽带网线(宽带猫、光猫);然后手机/笔记本电脑搜索连接到优酷路由宝的WiFi。优酷路由宝的默认WiFi名称是:Youku_开...

一键装机软件大全(一键装机下载)

1一键装机工具是一种自动化安装计算机操作系统以及常用软件的工具。2使用一键装机工具,需要先准备好需要安装的操作系统镜像和需要安装的软件列表,然后将它们放在一键装机工具所指定的位置。接下来,打开一键...

home键是什么意思苹果手机(home键是苹果手机哪个键)

就是手机屏幕正下方的那个圆形的按钮,就是苹果手机的home键,home键的作用比较大,可以用来设置指纹解锁,单机home键可以返回主屏幕界面,双击home键可以弹出后台应用程序可以进行清楚,还可以通过...

tplink说明书图片(tp-link路由器说明书步骤图)

第一步连接路由器WIFI在手机获取IP地址里找到路由器网关地址,第二步在浏览器地址栏输入路由器网关地址,之后会跳转到路由器管理员登录界面,输入账号密码就可以进入路由后台管理路由,如果提示路由器密码错误...

如何不安装flash玩4399(现在4399不提供flash如何玩游戏)

没有flash是玩不了的,需要开启flash才可以。1、首先打开浏览器,进入4399的游戏页面。2、进入游戏页面后,点击【已被屏蔽】文字。3、然后右上角会出现窗口,点击【管理】按钮。4、进入管理页面后...

chrome download apk(chromedownloadapk in english)

手机下载安装的第三方应用出现问题,无法正常使用,建议按照以下方法操作:1.关闭重新启动该应用。2.建议将此软件卸载重新安装尝试。3.更换其他版本尝试。4.更新下手机系统版本后安装尝试5.备份手机数据(...