sqldata_code

using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Transactions;
namespace sooyuu
{
    public class sy_sqldb
    {
        /// <summary>
        /// 后台管理库数据链接
        /// </summary>
        //public static readonly string ConnStr_sys = ConfigurationManager.ConnectionStrings["sql_sys"].ConnectionString;
        /// <summary>
        /// 搜娱商城数据库链接
        /// </summary>
        //public static readonly string ConnStr_shop = ConfigurationManager.ConnectionStrings["sql_netShop"].ConnectionString;
        /// <summary>
        /// 搜娱音乐数据库
        /// </summary>
        //public static readonly string ConnStr_music = ConfigurationManager.ConnectionStrings["sql_music"].ConnectionString;
       /// <summary>
       /// 搜娱软件数据库连接
       /// </summary>
        //public static readonly string ConnStr_p2p = ConfigurationManager.ConnectionStrings["sql_p2p"].ConnectionString;
        /// <summary>
        /// 文章数据库连接
        /// </summary>
        //public static readonly string ConnStr_article = ConfigurationManager.ConnectionStrings["sql_article"].ConnectionString;
        /// <summary>
        /// 论坛数据库链接
        /// </summary>
        //public static readonly string ConnStr_bbs = ConfigurationManager.ConnectionStrings["sql_bbs"].ConnectionString;

        /// <summary>
        /// 根据Web.Config配置节名称获取链接
        /// </summary>
        /// <param name="sqlConnStr"></param>
        /// <returns></returns>
        public static string ConnStr(string sqlConnStr)
        {
            return ConfigurationManager.ConnectionStrings[sqlConnStr].ConnectionString;
        }

        public static readonly string SystemName = ConfigurationManager.AppSettings["SystemName"];
        public static readonly int MD5Len = Convert.ToInt16(ConfigurationManager.AppSettings["MD5Len"]);


        #region "执行数据库操做"
        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.: 
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            //加入事务处理
            //using (TransactionScope TS = new TransactionScope())
            //{
                SqlCommand cmd = new SqlCommand();

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                    int val = cmd.ExecuteNonQuery();
                    //TS.Complete();
                    cmd.Parameters.Clear();
                    return val;
                }
            //}
        }

        /// <summary>
        /// 执行SQL语句返回影响行数(CommandType.Text)
        /// </summary>
        /// <param name="connectionString">数据库链接</param>
        /// <param name="cmdText">执行语句</param>
        /// <param name="commandParameters">SqlParameter</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            //加入事务处理
            //using (TransactionScope TS = new TransactionScope())
            //{
                SqlCommand cmd = new SqlCommand();

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, commandParameters);
                    int val = cmd.ExecuteNonQuery();
                    //TS.Complete();
                    cmd.Parameters.Clear();
                    return val;
                }
            //}
        }

        /// <summary>
        /// 重载ExecuteNonQuery方法
        /// </summary>
        /// <param name="connectionString">sql链接语句</param>
        /// <param name="cmdText">sql执行语句</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connectionString, string cmdText)
        {
            //加入事务处理
            //using (TransactionScope TS = new TransactionScope())
            //{
                SqlCommand cmd = new SqlCommand();
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, conn, cmdText);
                    int val = cmd.ExecuteNonQuery();
                    //TS.Complete();
                    return val;
                }
            //}
        }
        #endregion

        #region 执行Sql读语句
        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.: 
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to
            // close the connection throw code, because no datareader will exist, hence the
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }

        }
        /// <summary>
        /// 重载ExecuteReader方法
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to
            // close the connection throw code, because no datareader will exist, hence the
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }


        }
        /// <summary>
        /// 重载ExecuteReader方法
        /// </summary>
        /// <param name="connectionString">sql链接字符</param>
        /// <param name="cmdText">sql执行语句</param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string connectionString, string cmdText)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try
            {
                PrepareCommand(cmd, conn, cmdText);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return rdr;
            }          
            catch (Exception ex){
                conn.Close();
                string strMsg = ex.ToString();
                throw;
                //return strMsg;
            }
        }
        #endregion

        #region 回一条记录
        /// <summary>
        /// 返回一条记录
        /// </summary>
        /// <param name="mysql">SQL语句</param>
        /// <returns>返回值</returns>
        public static string GetOneData(string connectionString, string sqlString)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            try
            {
                SqlCommand cmd = new SqlCommand(sqlString, conn);
                string data = cmd.ExecuteScalar().ToString();
                return data;
            }
            catch (Exception ex)
            {
                string strErr = ex.Message;
                conn.Close();
                return null;
            }
            finally
            {
                conn.Close();
            }

        }
        #endregion

        #region 验证sql语句
        ////创建访问数据库的参数
        //SqlParameter[] paramList = { new SqlParameter("@ID", SqlDbType.Int, 5) };
        //paramList[0].Value = Phto_Id;
        //if(sy_sqldb.ExistsSQL(sql,sy_sqldb.ConnStr("sql_Mobile"),paramList))
        //添加:胡可
        public static bool ExistsSQL(string strSql,string connectionString, params SqlParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, connectionString,cmdParms);
            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>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, string connectionString ,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 new Exception(e.Message);
                    }
                }
            }
        }
        #endregion


        #region 返回一条记录的一个值[lika]
        /// <summary>
        /// 返回一条记录
        /// </summary>
        /// <param name="mysql">SQL语句</param>
        /// <returns>返回值</returns>
        public static string GetOneValue(string connectionString, string sqlString)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            try
            {
                SqlCommand cmd = new SqlCommand(sqlString, conn);
                object value = cmd.ExecuteScalar();
                if (value == null)
                {
                    return "";
                }
                else
                {
                    return Convert.ToString(value);
                }
               
            }
            catch
            {
                throw;
            }
            finally
            {
                conn.Close();
            }

        }
        #endregion

        #region "获取DataSet"
        /// <summary>
        /// 获取 DataSet
        /// </summary>
        /// <param name="dataset">一个已定义的 dataset值 </param>
        /// <param name="connectionString">链接字符</param>
        /// <param name="cmdTxt">查询语句</param>
        /// <returns></returns>
        /// 应用示例
        ///    string SqlSelect = "select columnId,columnName from [Bx_column]";
        ///    DataSet SqlDs = new DataSet();
        ///    ClassSqlDb.SelectRows(SqlDs, ClassSqlDb.Bx_ArticleConnectionString, SqlSelect);
        ///    gvColumn.DataSource = SqlDs;
        ///    gvColumn.DataBind();
        public static DataSet SelectRows(DataSet dataset, string connectionString, string cmdTxt)
        {
            SqlConnection conn = new SqlConnection(connectionString);

            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = new SqlCommand(cmdTxt, conn);
                adapter.Fill(dataset);
                return dataset;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }
        #endregion

        #region "添加参数数组到缓存"
        /// <summary>
        /// 添加参数数组到缓存
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }
        #endregion

        #region 准备SQL执行命令
        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, 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 = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        /// <summary>
        /// 重载SQL预备执行命令减少输入参数
        /// 添加人:胡可
        /// </summary>
        /// <param name="cmd">SQL命令</param>
        /// <param name="conn">SQL链接</param>
        /// <param name="trans">事务</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="cmdParms">传入参数</param>
        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);
                }
            }
        }
        /// <summary>
        /// 重载SQL预备执行命令减少输入参数
        /// </summary>
        /// <param name="cmd">SQL命令引用</param>
        /// <param name="conn">SQL链接</param>
        /// <param name="cmdText">SQL执行语句</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, string cmdText)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
        }
        #endregion

        #region "执行分页存储过程"
        /// <summary>
        /// 执行分页存储过程
        /// </summary>
        /// <param name="count">记录条数</param>
        /// <param name="page">当前页数</param>
        /// <param name="perpage">每页记录数</param>
        /// <param name="mainKeys">主键</param>
        /// <param name="field">字段</param>
        /// <param name="table">表名</param>
        /// <param name="condition">条件(不需要where)</param>
        /// <param name="orderby">排序(不需要order by,需要asc和desc字符)</param>
        /// <returns></returns>
        public static SqlDataReader Pagination(string connectionString, int count, int page, int perpage, string mainKeys, string field, string table, string condition, string orderby)
        {
            SqlParameter[] parms = new SqlParameter[]{
                new SqlParameter("@iRecordCount",SqlDbType.Float),
                new SqlParameter("@iPageCurr",SqlDbType.Int),
                new SqlParameter("@iPageSize",SqlDbType.Int),
                new SqlParameter("@sPkey",SqlDbType.NVarChar,50),
                new SqlParameter("@sField",SqlDbType.NVarChar,1000),
                new SqlParameter("@sTable",SqlDbType.NVarChar,500),
                new SqlParameter("@sCondition",SqlDbType.NVarChar,1000),
                new SqlParameter("@sOrder",SqlDbType.NVarChar,100)};
            parms[0].Value = count;
            parms[1].Value = page;
            parms[2].Value = perpage;
            parms[3].Value = mainKeys;
            parms[4].Value = field;
            parms[5].Value = table;
            parms[6].Value = condition;
            parms[7].Value = orderby;
            //parms[0].Direction = ParameterDirection.Output;

            SqlDataReader sdr = sy_sqldb.ExecuteReader(connectionString, CommandType.StoredProcedure, "SooYuu_Page", parms);
            //if (parms[0].Value != DBNull.Value)
            //{
            //    outCount = Convert.ToInt32(parms[0].Value);
            //}
            //else
            //{
            //    outCount = 0;
            //}
            return sdr;
        }
        #endregion

        #region 检查数据的有效性
        /// <summary>
        /// 检查SQL语句的有效性
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="sqlStr"></param>
        /// <returns></returns>
        public static Boolean checkDb(string connectionString, string sqlStr)
        {
            SqlDataReader sdr = sy_sqldb.ExecuteReader(connectionString, sqlStr);
            try
            {
                if (sdr.HasRows)
                {
                    if (sdr.Read())
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
                sdr.Close();
                throw;
            }
            finally
            {
                sdr.Close();
            }
        }
        #region  数据字段检测
        /// <summary>
        /// 数据字段检测
        /// </summary>
        /// <param name="connectionString">数据链接</param>
        /// <param name="fieldName">检测字段名</param>
        /// <param name="tableName">检测表名</param>
        /// <returns></returns>
        public static Boolean checkDb(string connectionString, string fieldName, string tableName,string where)
        {
            string _sql = "select top 1 " + fieldName + " from [" + tableName + "] where " + where;
            SqlDataReader sdr = sy_sqldb.ExecuteReader(connectionString, _sql);
            try
            {
                if (sdr.Read())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
                sdr.Close();
                throw;
            }
            finally
            {
                sdr.Close();
            }
        }
        #endregion  数据字段检测

        #endregion

        #region 执行查询语句,返回DataSet
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connectionString,string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, conn, null, CommandType.Text, 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;
                }
            }
        }
        #endregion 执行查询语句,返回DataSet


        #region 将Datareader转换为datatable
        /// <summary>
        /// 将DataReader转为DataTable
        /// 胡可
        /// </summary>
        /// <param name="DataReader">DataReader</param>
        public static DataTable ConvertdrTodt(SqlDataReader dataReader)
        {
            ///定义DataTable
            DataTable datatable = new DataTable();

            ///动态添加表的数据列
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                DataColumn mydc = new DataColumn();
                mydc.DataType = dataReader.GetFieldType(i);
                mydc.ColumnName = dataReader.GetName(i);
                datatable.Columns.Add(mydc);
            }

            ///添加表的数据
            while (dataReader.Read())
            {
                DataRow mydr = datatable.NewRow();
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    mydr[i] = dataReader[i].ToString();
                }
                datatable.Rows.Add(mydr);
                mydr = null;
            }
            ///关闭数据读取器
            dataReader.Close();
            return datatable;
        }
        #endregion

        /// <summary>
        /// 生成文件名(Path)
        /// </summary>
        /// <param name="serverStr">数据库服务器地址</param>
        /// <param name="table">表名</param>
        /// <param name="num">随机生成多少数字</param>
        /// <returns></returns>
        public static string GetHtmlName(string serverStr, string table, int num)
        {

            string _htm = sy_chars.GetRandomNum(num) + DateTime.Now.ToString("ddHHmmssfff");
            //检查是否存在重复的文章
            string _sql = string.Empty;
            switch (table)
            {
                case "sy_article":
                    _sql = "select A_Id from [sy_article] where A_Path='" + _htm + "'";
                    break;
                case "sy_downinfo":
                    _sql = "select D_Id from [sy_downinfo] where D_Path='" + _htm + "'";
                    break;
                case "m_xiezhen":
                    _sql = "select mx_id from [m_xiezhen] where mx_Path='" + _htm + "'";
                    break;
                case "m_singer":
                    _sql = "select msi_id from [m_singer] where msi_Path='" + _htm + "'";
                    break;
                case "B_OnlineBook":
                    _sql = "select O_Id from B_OnlineBook where O_Path='" + _htm + "'";
                    break;
                case "B_OnlineSection":
                    _sql = "select OS_Id from B_OnlineSection where OS_Path='" + _htm + "'";
                    break;
                case "B_OnlineChapter":
                    _sql = "select OC_Id from B_OnlineChapter where OC_Path='" + _htm + "'";
                    break;
                case "K_Article":
                    _sql = "select A_Id from [K_Article] where A_Path='" + _htm + "'";
                    break;
                case "G_Article":
                    _sql = "select A_Id from [G_Article] where A_Path='" + _htm + "'";
                    break;
                case "Brand":
                    _sql = "select Brnd_Id from [Brand] where Brnd_Path='" + _htm + "'";
                    break;

                case "Product":
                    _sql = "select Prdt_Id from [Product] where Prdt_Path='" + _htm + "'";
                    break;
                case "Photo":
                    _sql = "select Phto_Id from [Photo] where Phto_Path='" + _htm + "'";
                    break;
                case "Article":
                    _sql = "select A_id from [Article] where A_Path='" + _htm + "'";
                    break;

            }
            if (sy_sqldb.checkDb(sy_sqldb.ConnStr(serverStr), _sql))
            {
                return GetHtmlName(serverStr, table, num);
            }
            else
            {
                return _htm;
            }
        }


    }
}

你可能感兴趣的:(sql,exception,String,cmd,null,dataset)