using System; using System.Data; using System.Data.SqlClient; using System.IO; namespace RaywindStudio.DAL { /// <summary> /// MSSQL数据库操作类 /// </summary> public static class SqlHelper { /// <summary> /// 是否写调试信息 /// 执行成功写到C:\\DebugSQL.txt; /// 执行失败写到C:\\DebugTxt.txt; /// </summary> public static bool debug = false; #region Select /// <summary> /// Select查表 /// </summary> /// <param name="Columns">一条完整、直接执行的select语句</param> /// <param name="TableName">一条完整、直接执行的select语句</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>DataTable</returns> public static DataTable SelectTable(string Columns, string TableName, SqlParameter[] ConditionparamsPair, SqlConnection sqlconn) { string sql = "Select " + Columns + " From " + TableName + " Where 1=1 "; for (int i = 0; i < ConditionparamsPair.Length; i++) sql += " and " + ConditionparamsPair[i].ParameterName.Replace("@", "") + "=" + ConditionparamsPair[i].ParameterName; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(ConditionparamsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); using (DataTable dt = new DataTable()) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { try { debugSQL(cmd.CommandText); da.Fill(dt); return dt; } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("SelectTable:\n" + ex.Message); } } } } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("SelectTable:\n" + ex.Message); } } /// <summary> /// Select查表 /// </summary> /// <param name="Columns">一条完整、直接执行的select语句</param> /// <param name="TableName">一条完整、直接执行的select语句</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>DataTable</returns> public static DataTable SelectTable(string Columns, string TableName, SqlParameter ConditionparamsPair, SqlConnection sqlconn) { return SelectTable(Columns, TableName, new SqlParameter[] { ConditionparamsPair }, sqlconn); } /// <summary> /// Select查值 /// </summary> /// <param name="Columns">一条完整、直接执行的select语句</param> /// <param name="TableName">一条完整、直接执行的select语句</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>DataTable</returns> public static object SelectValue(string Columns, string TableName, SqlParameter[] ConditionparamsPair, SqlConnection sqlconn) { string sql = "Select " + Columns + " From " + TableName + " Where 1=1 "; for (int i = 0; i < ConditionparamsPair.Length; i++) sql += " and " + ConditionparamsPair[i].ParameterName.Replace("@", "") + "=" + ConditionparamsPair[i].ParameterName; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(ConditionparamsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteScalar(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("SelectValue:\n" + ex.Message); } } /// <summary> /// Select查值 /// </summary> /// <param name="Columns">一条完整、直接执行的select语句</param> /// <param name="TableName">一条完整、直接执行的select语句</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>DataTable</returns> public static object SelectValue(string Columns, string TableName, SqlParameter ConditionparamsPair, SqlConnection sqlconn) { return SelectValue(Columns, TableName, new SqlParameter[] { ConditionparamsPair }, sqlconn); } #endregion #region Insert /// <summary> /// 执行MSSQL插入表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int InsertCMD(string TableName, SqlParameter[] paramsPair, SqlConnection sqlconn) { string sql = "Insert into " + TableName + "("; for (int i = 0; i < paramsPair.Length; i++) sql += paramsPair[i].ParameterName.Replace("@", "") + ","; sql = sql.Substring(0, sql.Length - 1) + ") Values("; for (int j = 0; j < paramsPair.Length; j++) sql += paramsPair[j].ParameterName + ","; sql = sql.Substring(0, sql.Length - 1) + ")"; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(paramsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("InsertCMD:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行MSSQL插入表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int InsertCMD(string TableName, SqlParameter paramsPair, SqlConnection sqlconn) { return InsertCMD(TableName, new SqlParameter[] { paramsPair }, sqlconn); } /// <summary> /// 执行MSSQL插入表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="ColumnValues">ColumnValue键值对:弥补SqlParameter无法调用getdate()、year()等内部函数的不足。 /// 前后分别为Column和Value,添加在insert语句的column和value部分</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int InsertCMD(string TableName, SqlParameter[] paramsPair, string[,] ColumnValues, SqlConnection sqlconn) { string sql = "Insert into " + TableName + "("; for (int i = 0; i < paramsPair.Length; i++) sql += paramsPair[i].ParameterName.Replace("@", "") + ","; for (int ii = 0; ii < ColumnValues.GetLength(0); ii++) sql += ColumnValues[ii, 0] + ","; sql = sql.Substring(0, sql.Length - 1) + ") Values("; for (int j = 0; j < paramsPair.Length; j++) sql += paramsPair[j].ParameterName + ","; for (int jj = 0; jj < ColumnValues.GetLength(0); jj++) sql += ColumnValues[jj, 1] + ","; sql = sql.Substring(0, sql.Length - 1) + ")"; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(paramsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("InsertCMD:ExecuteNonQuery\n" + ex.Message); } } #endregion #region Update /// <summary> /// 执行MSSQL更新表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">查询条件,不需要where,默认列名:ColumnName=ParameterName.Replace("@","")</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int UpdateCMD(string TableName, SqlParameter[] paramsPair, SqlParameter[] ConditionparamsPair, SqlConnection sqlconn) { string sql = "Update " + TableName + " Set "; for (int i = 0; i < paramsPair.Length; i++) sql += paramsPair[i].ParameterName.Replace("@", "") + "=" + paramsPair[i].ParameterName + ","; sql = sql.Substring(0, sql.Length - 1) + " Where 1=1 "; for (int i = 0; i < ConditionparamsPair.Length; i++) sql += " and " + ConditionparamsPair[i].ParameterName.Replace("@", "") + "=" + ConditionparamsPair[i].ParameterName; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(paramsPair); cmd.Parameters.AddRange(ConditionparamsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("UpdateCMD:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行MSSQL更新表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="ColumnValues">ColumnValue键值对:弥补SqlParameter无法调用getdate()、year()等内部函数的不足。 /// 前后分别为Column和Value,添加在insert语句的column和value部分</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <param name="ConditionsColumnValues">ColumnValue键值对:弥补SqlParameter无法调用getdate()、year()等内部函数的不足。 /// 前后分别为Column和Value,添加在insert语句的column和value部分</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int UpdateCMD(string TableName, SqlParameter[] paramsPair, string[,] ColumnValues, SqlParameter[] ConditionparamsPair, string[,] ConditionsColumnValues, SqlConnection sqlconn) { string sql = "Update " + TableName + " Set "; for (int i = 0; i < paramsPair.Length; i++) sql += paramsPair[i].ParameterName.Replace("@", "") + "=" + paramsPair[i].ParameterName + ","; for (int j = 0; j < ColumnValues.GetLength(0); j++) sql += ColumnValues[j, 0] + "=" + ColumnValues[j, 1] + ","; sql = sql.Substring(0, sql.Length - 1) + " Where 1=1 "; for (int i = 0; i < ConditionparamsPair.Length; i++) sql += " and " + ConditionparamsPair[i].ParameterName.Replace("@", "") + "=" + ConditionparamsPair[i].ParameterName; for (int j = 0; j < ConditionsColumnValues.GetLength(0); j++) sql += " and " + ConditionsColumnValues[j, 0] + "=" + ConditionsColumnValues[j, 1]; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(paramsPair); cmd.Parameters.AddRange(ConditionparamsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("UpdateCMD:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行MSSQL更新表操作,默认列名:ColumnName=ParameterName.Replace("@","") /// </summary> /// <param name="TableName">表名称</param> /// <param name="paramsPair">SqlParameter</param> /// <param name="ColumnValues">ColumnValue键值对:弥补SqlParameter无法调用getdate()、year()等内部函数的不足。 /// 前后分别为Column和Value,添加在insert语句的column和value部分</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <param name="ConditionsColumnValues">ColumnValue键值对:弥补SqlParameter无法调用getdate()、year()等内部函数的不足。 /// 前后分别为Column和Value,添加在insert语句的column和value部分</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int UpdateCMD(string TableName, SqlParameter paramsPair, string[,] ColumnValues, SqlParameter ConditionparamsPair, string[,] ConditionsColumnValues, SqlConnection sqlconn) { return UpdateCMD(TableName, new SqlParameter[] { paramsPair }, ColumnValues, new SqlParameter[] { ConditionparamsPair }, ConditionsColumnValues, sqlconn); } #endregion #region Delete /// <summary> /// 执行MSSQL删除表内数据操作 /// </summary> /// <param name="TableName">表名称</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int DeleteCMD(string TableName, SqlParameter[] ConditionparamsPair, SqlConnection sqlconn) { string sql = "Delete From " + TableName + " Where 1=1 "; for (int i = 0; i < ConditionparamsPair.Length; i++) sql += " and " + ConditionparamsPair[i].ParameterName.Replace("@", "") + "=" + ConditionparamsPair[i].ParameterName; SqlCommand cmd = new SqlCommand(sql, sqlconn); cmd.Parameters.AddRange(ConditionparamsPair); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("DeleteCMD:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行MSSQL删除表内数据操作 /// </summary> /// <param name="TableName">表名称</param> /// <param name="sqlconn">一个SQL连接</param> /// <param name="ConditionparamsPair">SqlParameter</param> /// <returns>ExecuteNonQuery执行结果</returns> public static int DeleteCMD(string TableName, SqlConnection sqlconn, SqlParameter ConditionparamsPair) { return DeleteCMD(TableName, new SqlParameter[] { ConditionparamsPair }, sqlconn); } #endregion #region Exec Proc /// <summary> /// 执行存储过程,无返回值 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static void ExecProcNonReturn(string sqlString, SqlParameter[] parameters, SqlConnection sqlconn) { SqlCommand cmd = new SqlCommand(sqlString, sqlconn); cmd.Parameters.AddRange(parameters); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); cmd.ExecuteNonQuery(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("ExecProcNonReturn:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行存储过程,无返回值 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static void ExecProcNonReturn(string sqlString, SqlParameter parameters, SqlConnection sqlconn) { ExecProcNonReturn(sqlString, new SqlParameter[] { parameters }, sqlconn); } /// <summary> /// 执行存储过程,并直接返回执行的结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProc(string sqlString, SqlParameter[] parameters, SqlConnection sqlconn) { SqlCommand cmd = new SqlCommand(sqlString, sqlconn); cmd.Parameters.AddRange(parameters); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); debugSQL(cmd.CommandText); return cmd.ExecuteScalar(); } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("ExecProc:ExecuteScalar\n" + ex.Message); } } /// <summary> /// 执行存储过程,并直接返回执行的结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProc(string sqlString, SqlParameter parameters, SqlConnection sqlconn) { return ExecProc(sqlString, new SqlParameter[] { parameters }, sqlconn); } /// <summary> /// 执行存储过程,带一个返回参数并返回此参数的执行结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="parameter_out">SqlParameter.Direction = ParameterDirection.Output;</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProcWithOut(string sqlString, SqlParameter[] parameters, SqlParameter parameter_out, SqlConnection sqlconn) { SqlCommand cmd = new SqlCommand(sqlString, sqlconn); cmd.Parameters.AddRange(parameters); cmd.Parameters.Add(parameter_out); try { if (sqlconn.State != ConnectionState.Open) sqlconn.Open(); cmd.ExecuteNonQuery(); debugSQL(cmd.CommandText); return parameter_out.Value; } catch (Exception ex) { debugTxt(cmd.CommandText, ex); throw new Exception("ExecProc:ExecuteNonQuery\n" + ex.Message); } } /// <summary> /// 执行存储过程,带一个返回参数并返回此参数的执行结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameters">SqlParameter</param> /// <param name="parameter_out">SqlParameter.Direction = ParameterDirection.Output;</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProcWithOut(string sqlString, SqlParameter parameters, SqlParameter parameter_out, SqlConnection sqlconn) { return ExecProcWithOut(sqlString, new SqlParameter[] { parameters }, parameter_out, sqlconn); } /// <summary> /// 执行存储过程,无返回值 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static void ExecProcNonReturn(string sqlString, SqlConnection sqlconn) { ExecProcNonReturn(sqlString, new SqlParameter[] { }, sqlconn); } /// <summary> /// 执行存储过程,并直接返回执行的结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProc(string sqlString, SqlConnection sqlconn) { return ExecProc(sqlString, new SqlParameter[] { }, sqlconn); } /// <summary> /// 执行存储过程,带一个返回参数并返回此参数的执行结果 /// </summary> /// <param name="sqlString">存储过程执行语句,需包含Exec </param> /// <param name="parameter_out">SqlParameter.Direction = ParameterDirection.Output;</param> /// <param name="sqlconn">一个SQL连接</param> /// <returns>ExecuteNonQuery执行结果</returns> public static object ExecProcWithOut(string sqlString, SqlParameter parameter_out, SqlConnection sqlconn) { return ExecProcWithOut(sqlString, new SqlParameter[] { }, parameter_out, sqlconn); } #endregion #region Debug private static void debugSQL(string sql) { if (debug) { StreamWriter sw = new StreamWriter("C:\\DebugSQL.txt", true); sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\t" + sql); sw.AutoFlush = true; sw.Close(); sw.Dispose(); } } private static void debugTxt(string sql, Exception ee) { if (debug) { StreamWriter sw = new StreamWriter("C:\\DebugTxt.txt", true); sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\t" + sql + "\n" + ee.ToString()); sw.AutoFlush = true; sw.Close(); sw.Dispose(); } } #endregion #region Distinct /// <summary> /// 从DataRow集合中排除重复项,并返回一个DataTable /// </summary> /// <param name="drs">DataRow集合</param> /// <param name="ColumnName">筛选的条件列名</param> /// <param name="DataTableschemaClone">要将结果装入的空表的架构</param> /// <returns>DataTable</returns> public static DataTable DistInctTable(DataRow[] drs, string ColumnName, DataTable DataTableschemaClone) { try { DataTable dts = DataTableschemaClone.Clone(); foreach (DataRow dr in drs) dts.ImportRow(dr); for (int i = dts.Rows.Count - 1; i >= 0; i--) if (dts.Select(ColumnName + "=‘" + dts.Rows[i][ColumnName].ToString() + "‘").Length > 1) dts.Rows.RemoveAt(i); dts.AcceptChanges(); return dts; } catch (Exception ex) { throw new Exception("DistInctTable(From DataRow):\n" + ex.Message); } } /// <summary> /// 从DataTable中排除重复行,并返回一个DataTable /// </summary> /// <param name="dt">源DataTable</param> /// <param name="ColumnName">筛选的条件列名</param> /// <returns>DataTable</returns> public static DataTable DistInctTable(DataTable dt, string ColumnName) { try { for (int i = dt.Rows.Count - 1; i >= 0; i--) if (dt.Select(ColumnName + "=‘" + dt.Rows[i][ColumnName].ToString() + "‘").Length > 1) dt.Rows.RemoveAt(i); dt.AcceptChanges(); return dt; } catch (Exception ex) { throw new Exception("DistInctTable(From DataTable):\n" + ex.Message); } } #endregion } }
直接手写SQL数据类型的问题太多了。再次完善扩展,新项目开始使用。
时间: 2024-10-07 22:22:48