• DBHelper


    OracleHelper:

      //Oracle连接字符串:
      <connectionStrings>
        <add name="OracleConnection" connectionString="Password=***;User ID=***;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.**.**)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));" providerName="Oracle.ManagedDataAccess.Client;provider" />
      </connectionStrings>

      public
    static class OracleHelper { //数据库连接字符串(web.config来配置) public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["OracleConnection"].ToString(); #region 检查是否存在 /// <summary> /// 检查是否存在,存在返回true,不存在返回false /// </summary> /// <param name="strSql"></param> /// <returns></returns> public static bool Exists(string strSql) { using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleCommand myCmd = new OracleCommand(strSql, connection); try { object obj = myCmd.ExecuteScalar(); //返回结果的第一行一列 myCmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return false; } else { return true; } } catch (Exception ex) { throw ex; } } } #endregion #region 执行简单SQL语句 返回影响的记录数 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { OracleConnection connection = null; OracleCommand cmd = null; try { connection = new OracleConnection(connectionString); cmd = new OracleCommand(SQLString, connection); connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } finally { if (cmd != null) { cmd.Dispose(); } if (connection != null) { connection.Close(); connection.Dispose(); } } } #endregion #region 执行查询语句,返回SqlDataReader /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static OracleDataReader ExecuteReader(string strSQL) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(strSQL, connection); try { connection.Open(); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (OracleException e) { throw e; } finally { connection.Close(); } } #endregion #region 执行SQL查询语句,返回DataTable数据表 /// <summary> /// 执行SQL查询语句 /// </summary> /// <param name="sqlStr"></param> /// <returns>返回DataTable数据表</returns> public static DataTable GetDataTable(string sqlStr) { OracleConnection mycon = new OracleConnection(connectionString); OracleCommand mycmd = new OracleCommand(sqlStr, mycon); DataTable dt = new DataTable(); OracleDataAdapter da = null; try { mycon.Open(); da = new OracleDataAdapter(sqlStr, mycon); da.Fill(dt); } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { mycon.Close(); } return dt; } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet QueryDs(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); OracleDataAdapter command = new OracleDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.OracleClient.OracleException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 存储过程操作 /// <summary> /// 运行存储过程,返回datatable; /// </summary> /// <param name="storedProcName">存储过程名称</param> /// <param name="parameters">参数</param> /// <returns></returns> public static DataTable RunProcedureDatatable(string storedProcName, IDataParameter[] parameters) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet ds = new DataSet(); connection.Open(); OracleDataAdapter sqlDA = new OracleDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(ds); connection.Close(); return ds.Tables[0]; } } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名称</param> /// <param name="parameters">参数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters) { using (OracleConnection connection = new OracleConnection(connectionString)) { try { connection.Open(); OracleCommand command = new OracleCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter 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); } } int rows = command.ExecuteNonQuery(); return rows; } finally { connection.Close(); } } } /// <summary> /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand</returns> private static OracleCommand BuildQueryCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters) { OracleCommand command = new OracleCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter 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 #region 事务处理 /// <summary> /// 执行多条SQL语句(list的形式),实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> /// 调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。 public static int ExecuteSqlTran(List<String> SQLStringList) { using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); // 为事务创建一个命令 OracleCommand cmd = new OracleCommand(); cmd.Connection = connection; OracleTransaction tx = connection.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();//用Commit方法来完成事务 return count;// } catch { tx.Rollback();//出现错误,事务回滚! return 0; } finally { cmd.Dispose(); connection.Close();//关闭连接 } } } #endregion #region 事务处理 /// <summary> /// 执行多条SQL语句(字符串数组形式),实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> /// 调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。 public static int ExecuteTransaction(string[] SQLStringList, int p) { using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); // 为事务创建一个命令 OracleCommand cmd = new OracleCommand(); cmd.Connection = connection; OracleTransaction tx = connection.BeginTransaction();// 启动一个事务 cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < p; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit();//用Commit方法来完成事务 return count;// } catch { tx.Rollback();//出现错误,事务回滚! return 0; } finally { cmd.Dispose(); connection.Close();//关闭连接 } } } #endregion }

    MySQLHelper:

       //MySQL连接字符串

        <appSettings>
        <add key="ConnectionString" value="Server=192.168.**.**;Database=smbcore;Uid=root;Pwd=root;CharSet=utf8"/>
       </appSettings>

      public class MySQLHelper
        {
            //数据库连接字符串(web.config来配置)
            public static string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
    
            #region 公用方法
            /// <summary>
            /// 得到最大值
            /// </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 = GetSingle(strsql);
                if (obj == null)
                {
                    return 1;
                }
                else
                {
                    return int.Parse(obj.ToString());
                }
            }
            /// <summary>
            /// 是否存在
            /// </summary>
            /// <param name="strSql"></param>
            /// <returns></returns>
            public static bool Exists(string strSql)
            {
                object obj = GetSingle(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>
            /// 是否存在(基于MySqlParameter)
            /// </summary>
            /// <param name="strSql"></param>
            /// <param name="cmdParms"></param>
            /// <returns></returns>
            public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
            {
                object obj = GetSingle(strSql, 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;
                }
            }
            #endregion
    
            #region  执行简单SQL语句
    
            /// <summary>
            /// 执行SQL语句,返回影响的记录数
            /// </summary>
            /// <param name="SQLString">SQL语句</param>
            /// <returns>影响的记录数</returns>
            public static int ExecuteSql(string SQLString)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                    {
                        try
                        {
                            connection.Open();
                            int rows = cmd.ExecuteNonQuery();
                            return rows;
                        }
                        catch (MySql.Data.MySqlClient.MySqlException e)
                        {
                            connection.Close();
                            throw e;
                        }
                    }
                }
            }
    
            public static int ExecuteSqlByTime(string SQLString, int Times)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                    {
                        try
                        {
                            connection.Open();
                            cmd.CommandTimeout = Times;
                            int rows = cmd.ExecuteNonQuery();
                            return rows;
                        }
                        catch (MySql.Data.MySqlClient.MySqlException e)
                        {
                            connection.Close();
                            throw e;
                        }
                    }
                }
            }
            /// <summary>
            /// 执行多条SQL语句,实现数据库事务。
            /// </summary>
            /// <param name="SQLStringList">多条SQL语句</param>        
            public static int ExecuteSqlTran(List<String> SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;
                    MySqlTransaction 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;
                    }
                }
            }
            /// <summary>
            /// 执行带一个存储过程参数的的SQL语句。
            /// </summary>
            /// <param name="SQLString">SQL语句</param>
            /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
            /// <returns>影响的记录数</returns>
            public static int ExecuteSql(string SQLString, string content)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                    MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
                    myParameter.Value = content;
                    cmd.Parameters.Add(myParameter);
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
            /// <summary>
            /// 执行带一个存储过程参数的的SQL语句。
            /// </summary>
            /// <param name="SQLString">SQL语句</param>
            /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
            /// <returns>影响的记录数</returns>
            public static object ExecuteSqlGet(string SQLString, string content)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                    MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@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 (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
            /// <summary>
            /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
            /// </summary>
            /// <param name="strSQL">SQL语句</param>
            /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
            /// <returns>影响的记录数</returns>
            public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MySqlCommand cmd = new MySqlCommand(strSQL, connection);
                    MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
                    myParameter.Value = fs;
                    cmd.Parameters.Add(myParameter);
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
    
            /// <summary>
            /// 执行一条计算查询结果语句,返回查询结果(object)。
            /// </summary>
            /// <param name="SQLString">计算查询结果语句</param>
            /// <returns>查询结果(object)</returns>
            public static object GetSingle(string SQLString)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand(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 (MySql.Data.MySqlClient.MySqlException e)
                        {
                            connection.Close();
                            throw e;
                        }
                    }
                }
            }
            public static object GetSingle(string SQLString, int Times)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand(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 (MySql.Data.MySqlClient.MySqlException e)
                        {
                            connection.Close();
                            throw e;
                        }
                    }
                }
            }
            /// <summary>
            /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
            /// </summary>
            /// <param name="strSQL">查询语句</param>
            /// <returns>MySqlDataReader</returns>
            public static MySqlDataReader ExecuteReader(string strSQL)
            {
                MySqlConnection connection = new MySqlConnection(connectionString);
                MySqlCommand cmd = new MySqlCommand(strSQL, connection);
                try
                {
                    connection.Open();
                    MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    return myReader;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    throw e;
                }
    
            }
            /// <summary>
            /// 执行查询语句,返回DataSet
            /// </summary>
            /// <param name="SQLString">查询语句</param>
            /// <returns>DataSet</returns>
            public static DataSet Query(string SQLString)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        connection.Open();
                        MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                        command.Fill(ds, "ds");
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
            public static DataSet Query(string SQLString, int Times)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        connection.Open();
                        MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                        command.SelectCommand.CommandTimeout = Times;
                        command.Fill(ds, "ds");
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
    
            /// <summary>
            /// 执行查询语句,返回DataTable
            /// </summary>
            /// <param name="SQLString">查询语句</param>
            /// <returns>DataTable</returns>
            public static DataTable QueryTable(string SQLString)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        connection.Open();
                        MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                        command.Fill(dt);
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
            public static DataTable QueryTable(string SQLString, MySqlParameter[] cmdParms)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        connection.Open();
                        MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddRange(cmdParms);
                        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                        da.Fill(dt);
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
            public static DataTable GetCurrPageData(string strSql, MySqlParameter[] cmdParms, int pageSize, int pageIndex, out int recordCount, out int pageCount)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    recordCount = 0;
                    pageCount = 0;
                    DataTable dt = new DataTable();
                    try
                    {
                        connection.Open();
                        strSql += " limit " + pageSize * (pageIndex - 1) + ", " + pageSize + ";" + strSql + ";";
                        MySqlCommand cmd = new MySqlCommand(strSql, connection);
                        cmd.CommandType = CommandType.Text;
                        if (cmdParms != null && cmdParms.Length > 0)
                        {
                            cmd.Parameters.AddRange(cmdParms);
                        }
                        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        dt = ds.Tables[0];
                        recordCount = ds.Tables[1].Rows.Count;
                        pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(recordCount) / pageSize));
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
    
            public static DataTable GetCurrPageRecordData(string strSql, string strsql2, int pageSize, int pageIndex, out int recordCount, out int pageCount)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    recordCount = 0;
                    pageCount = 0;
                    DataTable dt = new DataTable();
                    try
                    {
                        connection.Open();
                        strSql += " limit " + pageSize * (pageIndex - 1) + ", " + pageSize + ";";
                        MySqlCommand cmd = new MySqlCommand(strSql, connection);
                        cmd.CommandType = CommandType.Text;
                        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        dt = ds.Tables[0];
                        //////////////////////////////////////////////////////////////////
                        cmd = new MySqlCommand(strsql2, connection);
                        cmd.CommandType = CommandType.Text;
                        da = new MySqlDataAdapter(cmd);
                        ds = new DataSet();
                        da.Fill(ds);
                        recordCount = int.Parse(ds.Tables[0].Rows[0]["COUNT(1)"].ToString());
                        pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(recordCount) / pageSize));
                    }
                    catch (MySql.Data.MySqlClient.MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
    
    
            #endregion
    
            #region 执行带参数的SQL语句
    
            /// <summary>
            /// 执行SQL语句,返回影响的记录数
            /// </summary>
            /// <param name="SQLString">SQL语句</param>
            /// <returns>影响的记录数</returns>
            public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        try
                        {
                            PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                            int rows = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            return rows;
                        }
                        catch (MySql.Data.MySqlClient.MySqlException e)
                        {
                            throw e;
                        }
                    }
                }
            }
    
    
            /// <summary>
            /// 执行多条SQL语句,实现数据库事务。
            /// </summary>
            /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
            public static int ExecuteSqlTran(Hashtable SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        int val = 0;
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            //循环
                            foreach (DictionaryEntry myDE in SQLStringList)
                            {
                                string cmdText = myDE.Key.ToString();
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                val = cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                        return val;
                    }
                }
            }
            /// <summary>
            /// 执行多条SQL语句,实现数据库事务。
            /// </summary>
            /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
            public static bool ExecuteSqlTran(List<MySqlCommand> commands)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        try
                        {
                            //循环
                            foreach (MySqlCommand myDE in commands)
                            {
                                myDE.Connection = conn;
                                int val = myDE.ExecuteNonQuery();
                            }
                            trans.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
    
            /// <summary>
            /// 执行多条SQL语句,实现数据库事务。
            /// </summary>
            /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
            public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            int indentity = 0;
                            //循环
                            foreach (DictionaryEntry myDE in SQLStringList)
                            {
                                string cmdText = myDE.Key.ToString();
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.InputOutput)
                                    {
                                        q.Value = indentity;
                                    }
                                }
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                int val = cmd.ExecuteNonQuery();
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.Output)
                                    {
                                        indentity = Convert.ToInt32(q.Value);
                                    }
                                }
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            }
            /// <summary>
            /// 执行一条计算查询结果语句,返回查询结果(object)。
            /// </summary>
            /// <param name="SQLString">计算查询结果语句</param>
            /// <returns>查询结果(object)</returns>
            public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        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 (MySql.Data.MySqlClient.MySqlException e)
                        {
                            throw e;
                        }
                    }
                }
            }
    
            /// <summary>
            /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
            /// </summary>
            /// <param name="strSQL">查询语句</param>
            /// <returns>MySqlDataReader</returns>
            public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
            {
                MySqlConnection connection = new MySqlConnection(connectionString);
                MySqlCommand cmd = new MySqlCommand();
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    cmd.Parameters.Clear();
                    return myReader;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    throw e;
                }
                //            finally
                //            {
                //                cmd.Dispose();
                //                connection.Close();
                //            }    
    
            }
    
            /// <summary>
            /// 执行查询语句,返回DataSet
            /// </summary>
            /// <param name="SQLString">查询语句</param>
            /// <returns>DataSet</returns>
            public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MySqlCommand cmd = new MySqlCommand();
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {
                        DataSet ds = new DataSet();
                        try
                        {
                            da.Fill(ds, "ds");
                            cmd.Parameters.Clear();
                        }
                        catch (MySql.Data.MySqlClient.MySqlException ex)
                        {
                            throw new Exception(ex.Message);
                        }
                        return ds;
                    }
                }
            }
    
    
            private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] 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 (MySqlParameter parameter in cmdParms)
                    {
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parameter);
                    }
                }
            }
    
            #endregion
        }
  • 相关阅读:
    【无旋转treap】模板
    线性选择算法好题
    【codeforces】305C GCD,容斥
    双连通
    线段树(3)
    线段树(2)
    线段树
    2015 Multi-University Training Contest 2
    2015 Multi-University Training Contest 1
    Codeforces Round #302 (Div. 1)
  • 原文地址:https://www.cnblogs.com/MrZheng/p/8881422.html
Copyright © 2020-2023  润新知