using JKTAC_LMIS.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace JKTAC_LMIS.DAL
{
public abstract class DbHelperSQL
{
public DbHelperSQL()
{ }
//定义连接字符串。
//protected static string ConnectionString = DecryptDBStr(ConfigurationManager.AppSettings["SQLConnectionString"], "zhangweilong");
protected static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
protected static SqlConnection Connection;
//定义数据库的打开和关闭方法
protected static void Open()
{
if (Connection == null)
{
Connection = new SqlConnection(ConnectionString);
}
if (Connection.State.Equals(ConnectionState.Closed))
{
Connection.Open();
}
}
protected static void Close()
{
if (Connection != null)
{
Connection.Close();
}
}
//判断用Sql查询的数据是否存在,true表示存在,False表示不存在
public static bool Exists(string strSql)
{
object obj = DbHelperSQL.GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
object obj = DbHelperSQL.GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
//返回SqlDataReader数据集,使用完后记得关闭SqlDataReader
public static SqlDataReader GetDataReader(string SqlString)
{
try
{
Open();
SqlCommand cmd = new SqlCommand(SqlString, Connection);
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
}
// 公有方法,获取数据,返回一个DataSet。
public static DataSet GetDataSet(string SqlString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(SqlString, connection))
{
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;
}
}
}
}
// 公有方法,获取数据,返回一个DataTable。
public static DataTable GetDataTable(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
return dataset.Tables[];
}
// 公有方法,获取数据,返回首行首列。
public static string GetSHSL(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
if (dataset.Tables[].Rows.Count > )
{
return Convert.ToString(dataset.Tables[].Rows[][].ToString());
}
else
{
return "";
}
}
// 公有方法,获取数据,返回首行首列的INT值。
public static string GetSHSLInt(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
if (dataset.Tables[].Rows.Count > )
{
return Convert.ToString(dataset.Tables[].Rows[][].ToString());
}
else
{
return "";
}
}
// 公有方法,获取数据,返回一个DataRow。
public static DataRow GetDataRow(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
if (dataset.Tables[].Rows.Count > )
{
return dataset.Tables[].Rows[];
}
else
{
return null;
}
}
// 公有方法,执行Sql语句。对Update、Insert、Delete为影响到的行数,其他情况为-1
public static int ExecuteSQL(String SqlString, Hashtable MyHashTb)
{
int count = -;
Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, Connection);
foreach (DictionaryEntry item in MyHashTb)
{
string[] CanShu = item.Key.ToString().Split('|');
if (CanShu[].ToString().Trim() == "string")
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
else if (CanShu[].ToString().Trim() == "int")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Int);
}
else if (CanShu[].ToString().Trim() == "text")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Text);
}
else if (CanShu[].ToString().Trim() == "datetime")
{
cmd.Parameters.Add(CanShu[], SqlDbType.DateTime);
}
else
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
cmd.Parameters[CanShu[]].Value = item.Value.ToString();
}
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
Close();
}
return count;
}
// 公有方法,执行Sql语句。对Update、Insert、Delete为影响到的行数,其他情况为-1
public static int ExecuteSQL(String SqlString)
{
int count = -;
Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, Connection);
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
Close();
}
return count;
}
// 公有方法,执行一组Sql语句。返回是否成功,采用事务管理,发现异常时回滚数据
public static bool ExecuteSQL(string[] SqlStrings)
{
bool success = true;
Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction();
cmd.Connection = Connection;
cmd.Transaction = trans;
try
{
foreach (string str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch
{
success = false;
trans.Rollback();
}
finally
{
Close();
}
return success;
}
// Trans
public static bool ExecuteSqlByTrans(List<SqlAndPrams> list)
{
bool success = true;
Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction();
cmd.Connection = Connection;
cmd.Transaction = trans;
try
{
foreach (SqlAndPrams item in list)
{
if (item.cmdParms==null)
{
cmd.CommandText = item.sql;
cmd.ExecuteNonQuery();
}
else
{
cmd.CommandText = item.sql;
cmd.CommandType = CommandType.Text;//cmdType;
cmd.Parameters.Clear();
foreach (SqlParameter parameter in item.cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
cmd.ExecuteNonQuery();
} }
trans.Commit();
}
catch(Exception e)
{
success = false;
trans.Rollback();
}
finally
{
Close();
}
return success;
}
// 执行一条计算查询结果语句,返回查询结果(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;
}
}
}
}
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;
}
}
}
}
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;
}
}
}
}
// 执行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;
}
}
}
}
//执行查询语句,返回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;
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State == ConnectionState.Open)
conn.Close();
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);
}
}
} #region 执行存储过程 Add by LQB 2014-12-18
public static object RunProcedure(string storedProcName, IDataParameter[] paramenters)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, paramenters);
object obj = command.ExecuteNonQuery();
//object obj = command.Parameters["@Output_Value"].Value; //@Output_Value和具体的存储过程参数对应
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
} 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;
}
#endregion
}
}

sql server DbHelperSQL类的更多相关文章

  1. C#操作SQL Server通用类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  2. SqlHelper简单实现(通过Expression和反射)8.Sql Server数据处理类

    这个类基本上就是调用EntityHelper,ExpressionHelper和ObjectHelper来进行各种完整SQL的拼接操作. using System; using System.Conf ...

  3. sql server操作类(本人自己写的)

    package com.mytest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepa ...

  4. SQL Server数据库连接类SQLHelper.cs

    using System; using System.Collections.Generic; using System.Text; using System.Configuration; using ...

  5. .NET 中数据访问用的 DBHelper(Sql Server) 类

    public class DBHelper { private static string DBConnectString = "Data Source=.;Initial Catalog= ...

  6. SQL Server int类型值最大2147483647(2^31 - 1)

    突发奇想,一个字增字段,假设每天增加1000条记录,多少年之后写不进int类型的字段了2147483647 / 1000 / 365 = 5883.51684109589041095890410958 ...

  7. DB通用类:SQL Server 通用类库

    SQLServer通用类A using System; using System.Data; using System.Data.SqlClient; using System.Collections ...

  8. SQL Server 审计操作概念

    概述 对于一般的数据库系统审计可能不太会被重视,但是对于金融系统就不一样的.金融系统对审计要求会很高,除了了记录数据库各种操作记录还可能会需要开发报表来呈现这些行为数据.使用SQL Server Au ...

  9. sql server 函数的自定义

    创建用户定义函数.这是一个已保存 Transact-SQL 或公共语言运行时 (CLR) 例程,该例程可返回一个值.用户定义函数不能用于执行修改数据库状态的操作.与系统函数一样,用户定义函数可从查询中 ...

随机推荐

  1. mysq建表参数设置

    建表的完整性约束: not null 与 default unique primary auto_increment foreign key 外键的变种  三种关系 一.介绍 约束条件与数据类型的宽度 ...

  2. Tomcat系列(5)——Tomcat配置详细部分

    Tomcat的架构图 Tomcat的组织结构 Tomcat是一个基于组件的服务器,它的构成组件都是可配置的,其中最外层的是Catalina servlet容器,其他组件按照一定的格式要求配置在这个顶层 ...

  3. 并发编程之CountDownLatch

    在前面的两篇文章中我们分别用volatile.notify()和wait()分别实现了一个场景,我们再来回顾一下前面的场景:在main方法中开启两个线程,其中一个线程t1往list里循环添加元素,另一 ...

  4. python3 练手实例1 计算三角形周长和面积

    def j(): a,b,c=map(float,input('请输入三角形三条边的长度,用空格隔开:').split()) if a>0 and b>0 and c>0 and a ...

  5. Exp1:PC平台逆向破解 20164314 郭浏聿

    一.实践目标 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任何用户输入的字符串. 该程序同时包含另一个代码片段,getS ...

  6. JavaScript之iframe页面间通信

    [1] iframe父子页面间通信 1.相互调用对方的方法 |> 子级页面调用父级页面 window.parent.父级页面方法(args) |> 父级页面调用子级页面 document. ...

  7. BlockChain 的跨链技术的重要性和必要性

    本期我们将从跨链技术的重要性和必要性.畅想区块链未来世界.什么是跨链.目前四种跨链技术的对比.构建EOS同构跨链体系群.EOCS跨链技术介绍.跨链通道.中继等几个层面带大家走进EOS跨链和EOCS的世 ...

  8. [转载]在termux上安装Kali Linux

    最近在手机上下了个Termux,然后想装个kali,就找到了这篇文章. 不过其中的命令有一处错误(在我进行配置的时候报错了): 命令应该是 ./atilo install kali

  9. SQL报错盲注

    嗯哼,这几天篮球比赛,天天训练,学习都耽搁了,DDCTF做了一会心态就爆炸了,蓝瘦,明天再打一场,希望能赢呢,打完就疯狂继续学习了.今天抽空又做了一些基本的SQL注入题目,墨者学院的一道报错注入的题目 ...

  10. golang interface类型转string等其他类型

    inter 是interface类型,转化为string类型是: str := inter .(string) 转为其他类型也类似