数据库助手(供ORM上层访问)

//--------------------------------------------------------------------------------
// 文件描述:数据库操作助手
// 文件作者:品浩
// 创建日期:2013/5/23
// 修改记录:上层web应用尽量参考查找类似http上下文 HttpContext.Current.Items["类对象"]  创造线程上下文来辅助加速系统,如线程内存槽
//--------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace lph.FrameWork
{

    /// <summary>
    /// 1.对于需要在页面直接传sql执行的,请自行过滤容易引起攻击的字符
    /// 2.此类是系统常用操作方法,能满足大部分需要了
    /// 3.不提倡使用存储过程,数据库尽量只做仓库的作用
    /// </summary>
    public abstract class DBHelper
    {
        //============================================================================================================================

        #region 判断存在

        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id(‘" + tableName + "‘) and [name]=‘" + columnName + "‘";
            object res = ExecuteScalar(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        /// <summary>
        /// 传sql语句检测记录是否存在,如select count(*)
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Exists(string strSql)
        {
            object obj = ExecuteScalar(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 查看表是否存在于数据库
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool ExistsTable(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N‘[" + TableName + "]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1";
            object obj = ExecuteScalar(strsql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region sql语句操作

        /// <summary>
        /// 执行SQL语句,根据受影响行数返回是否成功,用于增、删、改
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns>操作成功返回true,否则返回false</returns>
        public static bool ExecuteSql(string strSql)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            bool result = false;
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                cmd.CommandTimeout = 100;
                if (cmd.ExecuteNonQuery().ToBoolean())
                    result = true;
            }
            SqlConnectionPool.PutInstance(connection);
            connection = null;
            return result;
        }
        public static bool ExecuteSql(string strSql, Parameters parms)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            bool result = false;
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                foreach (SqlParameter parameter in parms.Entries)
                {
                    if (parameter != null)
                    {
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parameter);
                    }
                }
                cmd.CommandTimeout = 100;
                if (cmd.ExecuteNonQuery().ToBoolean())
                    result = true;
            }
            SqlConnectionPool.PutInstance(connection);
            connection = null;
            return result;
        }

        /// <summary>
        /// 执行SQL语句,从数据库中检索单个值
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns>返回结果(object)</returns>
        public static object ExecuteScalar(string strSql)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            object obj;
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                cmd.CommandTimeout = 100;
                obj = cmd.ExecuteScalar();
                if (Object.Equals(obj, null) || Object.Equals(obj, System.DBNull.Value))
                {
                    obj = null;
                }
            }
            SqlConnectionPool.PutInstance(connection);
            connection = null;
            return obj;
        }

        /// <summary>
        /// 执行Sql语句,返回输出参数的值
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static object ExecuteOutput(string strSql, Parameters parms)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            object obj;
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                foreach (SqlParameter parameter in parms.Entries)
                {
                    if (parameter != null)
                    {
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parameter);
                    }
                }
                cmd.CommandTimeout = 100;
                obj = cmd.ExecuteScalar();
                if (!string.IsNullOrEmpty(parms.OutPut))
                {
                    obj = cmd.Parameters[parms.OutPut].Value;
                }
            }
            SqlConnectionPool.PutInstance(connection);
            connection = null;
            return obj;
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string strSql)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                cmd.CommandTimeout = 100;
                SqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                connection = null;
                return Reader;
            }
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string strSql, Parameters parms, CommandType type)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            using (SqlCommand cmd = new SqlCommand(strSql, connection))
            {
                if (type == CommandType.StoredProcedure)
                {
                    cmd.CommandType = type;
                }
                cmd.CommandTimeout = 100;
                foreach (SqlParameter parameter in parms.Entries)
                {
                    if (parameter != null)
                    {
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parameter);
                    }
                }
                SqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                connection = null;
                return Reader;
            }
        }

        /// <summary>
        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string strSql, Parameters parms)
        {
            return ExecuteReader(strSql, parms, CommandType.Text);
        }
        /// <summary>
        /// 执行SQL语句,返回DataSet
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSet(string strSql)
        {
            SqlConnection connection = SqlConnectionPool.GetInstance();
            DataSet ds = new DataSet();
            SqlDataAdapter Adapter = new SqlDataAdapter(strSql, connection);
            Adapter.Fill(ds);
            SqlConnectionPool.PutInstance(connection);
            connection = null;
            return ds;
        }

        #endregion

        //============================================================================================================================

        #region 过滤及检测

        /// <summary>
        /// 过滤掉字符串中非数字、非分隔符的其他字符,返回数字列表字符串
        /// </summary>
        /// <param name="input">输入的数字序列字符串</param>
        /// <returns>数字列表字符串</returns>
        public static string ToValidId(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "-999";
            }

            string[] arrinput = input.Split(new char[] { ‘,‘ });
            string newinput = string.Empty;
            for (int i = 0; i < arrinput.GetLength(0); i++)
            {
                if (IsNumber(arrinput[i]))
                {
                    newinput = newinput + arrinput[i] + ",";
                }
            }

            if (newinput.Length > 0)
            {
                newinput = newinput.Substring(0, newinput.Length - 1);
            }
            else
            {
                return "-999";
            }

            return newinput;
        }

        /// <summary>
        /// 将字符串转换为数字字符串
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <returns>数字字符串</returns>
        public static string ToNumber(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "0";
            }

            if (!Regex.IsMatch(input, "^[+-]?[0-9]+[.]?[0-9]*$"))
            {
                return "0";
            }

            return input;
        }

        /// <summary>
        /// 检查字符串是否为数字字符串
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <returns>如果是数字字符串返回true,否则返回false</returns>
        public static bool IsNumber(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }

            return input.IsNumberSign();
        }

        /// <summary>
        /// 过滤掉字符串中会引起注入攻击的字符
        /// </summary>
        /// <param name="strchar">要过滤的字符串</param>
        /// <returns>已过滤的字符串</returns>
        public static string FilterBadChar(string strchar)
        {
            string newstrChar = string.Empty;
            if (string.IsNullOrEmpty(strchar))
            {
                newstrChar = string.Empty;
            }
            else
            {
                newstrChar = strchar.Replace("‘", string.Empty);
            }

            return newstrChar;
        }

        /// <summary>
        /// 过滤表字段
        /// </summary>
        /// <param name="fieldname">字段名</param>
        /// <returns>安全的字段名</returns>
        public static string FilterField(string fieldname)
        {
            if (string.IsNullOrEmpty(fieldname))
            {
                return string.Empty;
            }
            else
            {
                return Regex.Replace(fieldname, @"[^\w]", string.Empty);
            }
        }

        /// <summary>
        /// 过滤 In 类型 如: ‘xxx‘,‘xx‘
        /// </summary>
        /// <param name="inString">SQL语句的In子句中的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string FilterInString(string inString)
        {
            if (string.IsNullOrEmpty(inString))
            {
                return "‘‘";
            }

            string[] arrinput = Regex.Split(inString, "‘,‘", RegexOptions.IgnoreCase);
            string newinput = string.Empty;
            for (int i = 0; i < arrinput.GetLength(0); i++)
            {
                newinput += "‘" + FilterBadChar(arrinput[i]) + "‘,";
            }

            if (newinput.Length > 0)
            {
                newinput = newinput.Substring(0, newinput.Length - 1);
            }
            else
            {
                return "‘‘";
            }

            return newinput;
        }

        #endregion

        /// <summary>
        /// 打开数据库连接
        /// </summary>
        /// <param name="conn"></param>
        public static void OpenSql(SqlConnection conn)
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            return;
        }

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        /// <param name="conn"></param>
        public static void CloseSql(SqlConnection conn)
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            return;
        }

        /// <summary>
        /// 获取某表某列最大ID
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = ExecuteScalar(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        //==============================================================================================================================
    }
}
时间: 2024-10-25 00:36:22

数据库助手(供ORM上层访问)的相关文章

atitit.动态加载数据库配置in orm hibernate mybatis

atitit.动态加载数据库配置in orm 1. 动态加载数据库配置的优点::: 1 1.1. 组合多个配置文件... 1 1.2. 连接多个数据库 1 2. 基本的流程:::getCfg内存对象,,,,生成工厂类,在opoenSession 1 2.1. Hibernate动态添加配置流程 1 2.2. mybatis动态添加配置流程 1 2.3. #===hb code 2 3. 参考 3 1. 动态加载数据库配置的优点::: 1.1. 组合多个配置文件... 1.2. 连接多个数据库 2

数据库助手类 DBHelper

using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Reflection; /// <summary> /// 数据库助手 /// @浅时光 /// #[email protected] /// </summary> name

C# SQL数据库助手类2.0(自用)

1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Data; 5 using System.Data.SqlClient; 6 using System.Text; 7 8 namespace YcTools 9 { 10 /// <summary>C# SQL数据库助手类2.0</summary> 11 public class YSql

基于redis缓存数据库实现lnmp架构高速访问

how-缓存加速 使用nosql数据库: 如redis,mongodb,memcache what-redis redis 是一个高性能的 key-value 数据库. 1) redis 的出现,很大程度弥补了memcached 这类 key-value 存储的不足(只能存入内存). 2)它支持的数据类型比memcache多,包括了 Python,Ruby,Erlang,PHP 客户端... 3)Redis 的所有数据都是保存在内存中,两种同步模式 A>半持久化模式:RDB(全量同步) i>R

Oracle 数据库中不同事务并发访问的问题

现象 以SQL/Helper为例,打开不同的SQL窗口,对同一个表格进行操作,如下所示. 窗口1:当执行更新任务.紧接着执行查询时获得一组查询结果.结果是对的. 窗口2:而在另外一个SQL查询窗口中执查询,却得到更新前的结果. 当关闭窗口1时,执行窗口2,发现出现正确的更新结果. 分析 初步分析是数据库的并发访问的问题.当在窗口1中执行更新操作,对数据表格的引用并未有消除,而是在数据库中产生了针对当前事务的副本结果.而窗口2所针对的查询还是旧的更新前的数据库原本.当关闭窗口1后,数据库中的表格被

如何让mysql数据库允许被远程连接访问(业务机连数据机)

点击链接时,弹出错误提示:  ERROR 1130: Host '192.168.1.3' is not allowed to connect to this MySQL server  第一:更改 "mysql" 数据库里的 "user" 表里的 "host" 项,从"localhost"改称'%'. 然后新建查询 输入:flush rivileges(刷新系统权限表) 或者新加条记录,"host" 项为

Yii2 数据库Active Record(ORM)

ACTIVE RECORD(ORM) 参考:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html namespace app\models; use yii\db\ActiveRecord; class Customer extends ActiveRecord { const STATUS_ACTIVE = 'active'; const STATUS_DELETED = 'deleted'; public static

Android数据库:通过JDBC直接访问MySql

关于通过JDBC访问本地MySql数据库的一篇文章http://blog.csdn.net/leelit/article/details/41044187,昨天学完JDBC访问本地数据库后就想,怎样可以远程访问数据库,真正使其成为一个服务器.后面又联想起自己之间做的一个单机版外卖订餐App,如果可以使其通过数据库来维护,那才是一款真正有意义的App.后面又搜了一下远程访问数据库的方法很快就找到了答案:http://www.cnblogs.com/xd502djj/archive/2011/04/

还原数据库出现“未获得排他访问”解决方法(杀死数据库连接的存储过程sqlserver)

在master数据库下创建存储过程如下: createproc killspid (@dbnamevarchar(20)) as begin declare@sqlnvarchar(500) declare@spidint set@sql='declare getspid cursor for select spid from sysprocesses where dbid in (select dbid from sysdatabases where name=' +@dbname+' )'