DBHelp数据库操作语句

 

namespace Transformation
{
    public class DBHelper
    {
        /// 


        /// Default Connection String
        /// 
        public static string strDefaultConnectingString = @"";
        /// 
        /// Insert String Into Quotion
        /// 
        /// String To Be Inserted
        ///  Quoted String
        public static string GetQuotedString(string v)
        {
            string result = string.Empty;
            try
            {
                result = v.Replace("'", "''");
                result = String.Format("'{0}'", result);
            }
            catch(Exception e)
            {
                throw new Exception("String Error: Cannot Get Quoted String\\n"+e.Message);
            }
            return result;
        }
        /// 
        /// Insert String Into Quotion Ever If It Is Null
        /// 
        /// String To Be Inserted
        ///  Quoted String
        public static string GetQuotedStringIncludingNull(string v)
        {
            if (string.IsNullOrEmpty(v))
                return "NULL";
            return GetQuotedString(v);
        }
        /// 
        /// Get Connection String By Hospital Name
        /// 
        /// Original Connection String
        /// Name Of Hospital
        ///  Connection String For Appointed Hospital
        public static string GetConnectingStringByHospitalName(string conn, string hospname)
        {
            string result = conn;
            string key = "Initial Catalog=";
            try
            {
                int idx = result.IndexOf(key);
                idx = idx + key.Length;
                int idx2 = result.IndexOf(";", idx);
                key = result.Substring(idx, idx2 - idx);
                result = result.Replace(key, hospname);
            }
            catch (Exception e)
            {
                throw new Exception("String Error: Cannot Get Connection String By Hospital Name\\n"+e.Message);
            }
            return result;
        }
        /// 
        /// Get Sql Connection By Appointed Connection String
        /// 
        /// Connnection String
        ///  Sql Connection
        public static SqlConnection GetConnection(string connstr)
        {
            SqlConnection conn = new SqlConnection();
            try
            {
                conn.ConnectionString = connstr;
                conn.Open();
                return conn;
            }
            catch (SqlException ex)
            {
                conn.Close();
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error: Cannot Get Database Connection\\n" + errormessage);
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception("DB Error: Connectiong Is Wrong!\\n"+ex.Message); ;
            }
        }
        /// 
        /// Get Sql Connection By Default Connection String
        /// 
        ///  Sql Connection
        public static SqlConnection GetConnection()
        {
            return GetConnection(strDefaultConnectingString);
        }
        /// 
        /// Get DataTable By Sql Statement And Connection String 
        /// 
        /// Sql Statement
        /// Connection String
        ///  DataTable Got
        public static DataTable GetTable(string sql, string connstr)
        {
            DataTable result = new DataTable();
            SqlConnection conn = null;
            try
            {
                conn = GetConnection(connstr);
                SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
                adapter.Fill(result);
                return result;
            }
            catch (SqlException e)
            {
                conn.Close();
                conn.Dispose();
                string exceptionerror = GetExceptionInfo(e);
                throw new Exception("DB Error: Cannot Get Table\\n" + exceptionerror);
            }
        }
        /// 
        /// Get DataTable By Sql Statement And Default Connection String 
        /// 
        /// Sql Statement
        ///  DataTable Got
        public static DataTable GetTable(string sql)
        {
            return GetTable(sql, strDefaultConnectingString);
        }
        /// 
        /// Get String From DataRow By FieldName
        /// 
        /// Name Of Field
        /// DataRow
        ///  String Got
        public static string GetStringByRowAndFieldName(System.Data.DataRow row, string fn)
        {
            string result = "";
            try
            {
                if (row[fn] == DBNull.Value)
                    return result;
                result = row[fn].ToString().Trim();
                return result;
            }
            catch(SqlException e)
            {
                string exceptionerror = GetExceptionInfo(e);
                throw new Exception("DB Error: Cannot Get String By Row And Field Name\\n" + exceptionerror);
            }
        }
        /// 
        /// Get Int From DataRow By FieldName
        /// 
        /// Name Of Field
        /// DataRow
        ///  Int Got
        public static int GetIntByRowAndFieldName(System.Data.DataRow row, string fn)
        {
            int result = 0;
            try
            {
                if (row[fn] == DBNull.Value)
                    return 0;
                result = int.Parse(row[fn].ToString());
                return result;
            }
            catch (SqlException e)
            {
                string exceptionerror = GetExceptionInfo(e);
                throw new Exception("DB Error: Cannot Get Int By Row And Field Name\\n" + exceptionerror);
            }
        }
        /// 
        /// Get String By Sql Statement And Specified Connection String
        /// 
        /// Sql Statement
        /// Connection String
        ///  String Got
        public static string GetStringBySql(string sql, string connstr)
        {
            string result = "";
            DataTable dt = GetTable(sql, connstr);
            if (dt == null)
                return result;
            if (dt.Rows.Count <= 0)
<= 0)
<= 0)
                return result;
            if (dt.Rows[0][0] == DBNull.Value)
                return result;
            return dt.Rows[0][0].ToString().Trim();
        }
        /// 
        /// Get String By Sql Statement, Parameters And Specified Connnection String 
        /// 
        /// Sql Statement
        /// Connection String
        /// Parameters Of Sql Statement
        ///  String Got
        public static string GetStringBySql(string sql, string connstr, SqlParameter[] para)
        {
            string result = "";
            DataTable dt = GetTable(sql, connstr, para);
            if (dt == null)
                return result;
            if (dt.Rows.Count <= 0)
<= 0)
<= 0)
                return result;
            if (dt.Rows[0][0] == DBNull.Value)
                return result;
            return dt.Rows[0][0].ToString().Trim();
        }
        /// 
        /// Get String List From DataTable By Field Name
        /// 
        /// DataTable
        /// Name Of Field
        ///  String List
        public static List  GetStringListByFieldName(DataTable dt, string fn)
        {
            List  result = new List ();
            foreach (DataRow dr in dt.Rows)
            {
                result.Add(GetStringByRowAndFieldName(dr, fn));
            }
            return result;
        }
        /// 
        /// Get DataTable By Sql Statement, Paramenters And Specified Connection String
        /// 
        /// Connection String
        /// Parameters Of Sql Statement
        /// Sql Statement
        ///  DataTable Got
        public static DataTable GetTable(string sql, string connstr, SqlParameter[] parameters)
        {
            DataTable result = new DataTable();
            try
            {
                using (SqlConnection conn = GetConnection(connstr))
                {
                    using (SqlCommand command = new SqlCommand(sql, conn))
                    {
                        command.CommandType = CommandType.Text;
                        if (parameters != null)
                        {
                            foreach (SqlParameter parameter in parameters)
                            {
                                command.Parameters.Add(parameter);
                            }
                        }
                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        adapter.Fill(result);
                    }
                }
            }
            catch (SqlException ex)
            {
                string exceptionerror = GetExceptionInfo(ex);
                throw new Exception("DB Error: Cannot Get Table" + exceptionerror);
            }
            return result;
        }
        #region Common Methods

        /// 


        /// Get Exception Info
        /// 
        /// Sql Exception
        ///  Info Of Sql Exception
        public static string GetExceptionInfo(SqlException ex)
        {
            StringBuilder errorMessage = new StringBuilder();
            for (int i = 0; i < ex.errors.count; i++)
< ex.errors.count; i++)
< ex.errors.count; i++)
            {
                errorMessage.Append("Index #" + i + "\\n" +
                    "Message: " + ex.Errors[i].Message + "\\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\\n" +
                    "Source: " + ex.Errors[i].Source + "\\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\\n");
            }
            return errorMessage.ToString();
        }
        /// 
        /// Build SqlCommand For Querying
        /// 
        /// Sql Connection
        /// Name Of Stored Proc
        /// Parameters Of Stored Proc
        ///  Built SqlCommand For Querying
        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)
                {

                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        /// 


        /// Prepare Sql Command
        /// 
        /// Sql Command
        /// Sql Connection
        /// Sql Transaction
        /// Command Text
        /// Parameters Of Command
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                else if (conn.State == System.Data.ConnectionState.Broken)
                {
                    conn.Close();
                    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);
                    }
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string exceptionerror = GetExceptionInfo(ex);
                throw new Exception("DB Parms Error:" + exceptionerror);
            }
        }
        /// 
        /// Judge If Field Exists In Table
        /// 
        /// Name Of Table
        /// Name Of Field
        ///  Result Of Judgement
        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 = GetSingleData(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        /// 


        /// Get MaxID In Table
        /// 
        /// Name Of ID Field
        /// Name Of Table
        ///  MaxID
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingleData(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        /// 
        /// Judge If Data Satisfying Condition Exists
        /// 
        /// Sql Statement
        ///  Result Of Judgement
        public static bool Exists(string strSql)
        {
            object obj = GetSingleData(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;
            }
        }
        /// 
        /// Judge If Table Exists
        /// 
        /// Name Of Table
        ///  Result Of Judgement
        public static bool TableExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
            object obj = GetSingleData(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;
            }
        }
        /// 
        /// Judge If Data Satisfying Condition Exists
        /// 
        /// Sql Statement
        /// Parameters Of Sql Statement
        ///  Result Of Judgement
        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = GetSingleData(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  Execute Simple Sql

        /// 


        /// Execute SQL With Default Connection String
        /// 
        /// Sql Statement
        ///  Count Of Rows Affected
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (SqlException ex)
                    {
                        connection.Close();
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }


        /// 


        /// Execute SQL With Specified Connection String
        /// 
        /// Sql Statement
        ///  Count Of Rows Affected
        public static int ExecuteSql(string connectionstr, string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (SqlException ex)
                    {
                        connection.Close();
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }
        /// 
        /// Execute SQL In Appointed Time
        /// 
        /// Sql Statement
        /// Count Of Second
        ///  Count Of Rows Affected
        //public static int ExecuteSqlByTime(string SQLString, int seconds)
        //{
        //    using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
        //    {
        //        using (SqlCommand cmd = new SqlCommand(SQLString, connection))
        //        {
        //            try
        //            {
        //                connection.Open();
        //                cmd.CommandTimeout = seconds;
        //                int rows = cmd.ExecuteNonQuery();
        //                return rows;
        //            }
        //            catch (System.Data.SqlClient.SqlException e)
        //            {
        //                connection.Close();
        //                throw e;
        //            }
        //        }
        //    }
        //}

        /// 


        /// Excute Multiple SQL Statement In DataBase Transaction
        /// 
        /// String List Of Multiple Sql Statement
        public static int ExecuteSqlTran(List  SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(strDefaultConnectingString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < sqlstringlist.count; n++)
< sqlstringlist.count; n++)
< sqlstringlist.count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch (SqlException ex)
                {
                    tx.Rollback();
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }

            }
        }


        /// 


        /// Excute Multiple SQL Statement With Specified Connection String In Database Transaction
        /// 
        /// Connection String
        /// String List Of Multiple Sql Statement
        public static int ExecuteSqlTran(string connectionstr, List  SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionstr))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < sqlstringlist.count; n++)
< sqlstringlist.count; n++)
< sqlstringlist.count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch (SqlException ex)
                {
                    tx.Rollback();
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }

            }
        }

        /// 


        /// Get Single Object By Sql Statement
        /// 
        /// Sql Statement
        ///  Object Got
        public static object GetSingleData(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
            {
                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 (SqlException ex)
                    {
                        connection.Close();
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }


        /// 


        /// Get Single Object By Sql Statement And Specified Connection String
        /// 
        /// Sql Statement
        /// Connection String
        ///  Object Got
        public static object GetSingleData(string connectionstr, string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                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 (SqlException ex)
                    {
                        connection.Close();
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }
        /// 
        /// Get SqlDataReader By Sql Statement
        /// 
        /// Sql Statement
        ///  SqlDataReader Got
        public static SqlDataReader GetDataReader(string strSQL)
        {
            SqlConnection connection = new SqlConnection(strDefaultConnectingString);
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }

        }

        /// 


        /// Get SqlDataReader By Sql Statement And Specified Connection String
        /// 
        /// Sql Statement
        /// Connection String
        ///  SqlDataReader Got
        public static SqlDataReader GetDataReader(string connectionstr, string strSQL)
        {
            SqlConnection connection = new SqlConnection(connectionstr);
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }

        }
        /// 


        /// Get DataSet By Sql Statement
        /// 
        /// Sql Statement
        ///  DataSet Got
        public static DataSet GetDataSet(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SqlException ex)
                {
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }
                return ds;
            }
        }

        /// 


        /// Get DataSet By Sql Statement And Specified Connection String
        /// 
        /// Sql Statement
        /// Connection String
        ///  DataSet Got
        public static DataSet GetDataSet(string connectionstr, string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SqlException ex)
                {
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }
                return ds;
            }
        }
        #endregion

        #region Execute StoredProc

 

        /// 


        /// Get SqlDataReader By Stored Proc With Specified Parameters 
        /// 
        /// Name Of Stored Proc
        /// Parameters Of Stored Proc
        ///  SqlDataReader Got
        public static SqlDataReader GetDataReaderFromProc(string storedProcName, IDataParameter[] parameters)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
                {
                    SqlDataReader returnReader;
                    connection.Open();
                    SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                    command.CommandType = CommandType.StoredProcedure;
                    returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
                    return returnReader;
                }
            }
            catch (SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }

        }

        /// 


        /// Get SqlDataReader By Stored Proc With Assigned Parameters And Specified Connection String
        /// 
        /// Connection String
        /// Name Of Stored Proc
        /// Parameters Of Stored Proc
        ///  SqlDataReader
        public static SqlDataReader GetDataReaderFromProc(string connectionstr, string storedProcName, IDataParameter[] parameters)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionstr))
                {
                    SqlDataReader returnReader;
                    connection.Open();
                    SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
                    command.CommandType = CommandType.StoredProcedure;
                    returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
                    return returnReader;
                }
            }
            catch (SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }

        }

        /// 


        /// Get SqlDataSet With Specified Table Name By Stored Proc With Specified Parameters 
        /// 
        /// Name Of Stored Proc
        /// Parameters Of Store Proc
        /// Name Of Table
        ///  SqlDataSet Got
        public static DataSet GetDataSetFromProc(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
                {
                    DataSet dataSet = new DataSet();
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataSet, tableName);
                    connection.Close();
                    return dataSet;
                }
            }
            catch (SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }
        }
        /// 
        /// Get SqlDataSet With Specified Table Name By Stored Proc With Specified Parameters And Specified Connection String
        /// 
        /// Connection String
        /// Name Of Stored Proc
        /// Parameters Of Store Proc
        /// Name Of Table
        ///  SqlDataSet Got
        public static DataSet GetDataSetFromProc(string connectionstr, string storedProcName, IDataParameter[] parameters, string tableName)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionstr))
                {
                    DataSet dataSet = new DataSet();
                    connection.Open();
                    SqlDataAdapter sqlDA = new SqlDataAdapter();
                    sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                    sqlDA.Fill(dataSet, tableName);
                    connection.Close();
                    return dataSet;
                }
            }
            catch (SqlException ex)
            {
                string errormessage = GetExceptionInfo(ex);
                throw new Exception("DB Error:" + errormessage);
            }
        }


        /// 


        /// Execute Proc With Specified Parameters
        /// 
        /// Name Of Stored Proc
        /// Parameters Of Store Proc
        /// Count Of Rows Affected
        ///  Value Of Parameter ReturnValue
        public static int ExecuteProc(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
            {
                try
                {
                    int result;
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                    result = (int)command.Parameters["ReturnValue"].Value;
                    return result;
                }
                catch (SqlException ex)
                {
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }
            }
        }

        /// 


        /// Execute Proc With Specified Parameters And Connection String  
        /// 
        /// Name Of Stored Proc
        /// Parameters Of Store Proc
        /// Count Of Rows Affected
        /// Connection String
        ///  Value Of Parameter ReturnValue
        public static int ExecuteProc(string connectionstr, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                try
                {
                    int result;
                    connection.Open();
                    SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                    rowsAffected = command.ExecuteNonQuery();
                    result = (int)command.Parameters["ReturnValue"].Value;
                    return result;
                }
                catch (SqlException ex)
                {
                    string errormessage = GetExceptionInfo(ex);
                    throw new Exception("DB Error:" + errormessage);
                }
            }
        }

        /// 


        /// Bulid SqlCommand Which Returns Int 
        /// 
        /// Connection String
        /// Name Of Stored Proc
        /// Parameters Of Store Proc
        ///  SqlCommand Built
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion

        #region Execute Sql With Parameters

 

        /// 


        /// Execute Sql Statement With Specified Parameters
        /// 
        /// Sql Statement
        /// Parameters Of Sql Statement
        ///  Count Of Rows Affected
        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(strDefaultConnectingString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (SqlException ex)
                    {
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }

        /// 


        /// Execute Sql Statement With Specified Connection String And Parameters
        /// 
        /// Sql Statement
        /// Parameters Of Sql Statement
        /// Connection String
        ///  Count of Rows Affected
        public static int ExecuteSql(string connectionstr, string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (SqlException ex)
                    {
                        string errormessage = GetExceptionInfo(ex);
                        throw new Exception("DB Error:" + errormessage);
                    }
                }
            }
        }
        #endregion

    }
}

 

你可能感兴趣的:(C#,sql语句)