1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249 |
- using SXLibrary;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MOKA_Factory_Tools.Database
- {
- class DbHelper
- {
- #region 公共方法
- /// <summary>
- /// 是否存在该连接对象
- /// </summary>
- /// <param name="connectionString"></param>
- /// <returns></returns>
- public static bool IsConnectionExists(string connectionString)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- try
- {
- if (connection.State != ConnectionState.Open)
- connection.Open();
- connection.Close();
- return true;
- }
- catch(Exception e)
- {
- Log.WriteErrorLog(string.Format("{0}", e.Message));
- }
- }
- return false;
- }
- /// <summary>
- /// 表字段是否存在;
- /// </summary>
- /// <param name="tableName"></param>
- /// <param name="columnName"></param>
- /// <returns></returns>
- public static bool IsColumnExists(string connectionString, string tableName, string columnName)
- {
- string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
- object res = GetSingle(sql, connectionString);
- if (res == null)
- {
- return false;
- }
- return Convert.ToInt32(res) > 0;
- }
- /// <summary>
- /// 表是否存在;
- /// </summary>
- /// <param name="tableName"></param>
- /// <returns></returns>
- public static bool IsTableExists(string connectionString, string tableName)
- {
- string strsql = "select count(*) from sysobjects where id = object_id(N'[" + tableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
- object obj = GetSingle(strsql, connectionString);
- int cmdresult;
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- cmdresult = 0;
- }
- else
- {
- cmdresult = int.Parse(obj.ToString());
- }
- if (cmdresult == 0)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- /// <summary>
- /// 视图是否存在
- /// </summary>
- /// <param name="TableName"></param>
- /// <returns></returns>
- public static bool IsViewsExists(string connectionString, string viewsName)
- {
- try
- {
- string strsql = "SELECT count([object_id]) as objCount FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[" + viewsName + "]')";
- //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
- object obj = GetSingle(strsql, connectionString);
- 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;
- }
- }
- catch
- {
- }
- return false;
- }
- public static int GetMaxID(string connectionString, string FieldName, string TableName, string strWhere = "")
- {
- string strsql = "select max(" + FieldName + ")+1 from " + TableName;
- if (strWhere.Trim() != "")
- {
- strsql += (" where 1=1 and (" + strWhere + ")");
- }
- object obj = GetSingle(connectionString, strsql);
- if (obj == null)
- {
- return 1;
- }
- else
- {
- return int.Parse(obj.ToString());
- }
- }
- public static bool Exists(string connectionString, string strSQL)
- {
- int cmdresult;
- object obj = GetSingle(connectionString, strSQL);
- 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;
- }
- }
- public static bool Exists(string connectionString, string strSQL, params SqlParameter[] cmdParms)
- {
- object obj = GetSingle(connectionString, 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;
- }
- }
- /// <summary>
- /// 获取时间为"1900-01-01"的日期对象
- /// </summary>
- /// <returns></returns>
- public static DateTime GetNullDateTime()
- {
- return Convert.ToDateTime("1900-01-01");
- }
- /// <summary>
- /// 全局ID GUID获取19位的唯一数字序列
- /// </summary>
- /// <returns></returns>
- public static long GenerateId()
- {
- byte[] buffer = Guid.NewGuid().ToByteArray();
- return BitConverter.ToInt64(buffer, 0);
- }
- /// <summary>
- /// 返回指定类型是否为允许为null的 Nullable泛型对象
- /// </summary>
- /// <param name="_type"></param>
- /// <returns>是Nullable泛型对象为 true 否则为 false</returns>
- public static bool IsNullable(Type _type)
- {
- bool bl = _type.Name.ToLower().Contains("Nullable".ToLower());
- return bl;
- }
- /// <summary>
- /// 验证一个类的完全限定名中是否以“system.”开头
- /// </summary>
- /// <param name="classFullName"></param>
- /// <returns>以“system.”开头为 true 否则为 false </returns>
- public static bool VerificationClassFullNameIsSystem(string classFullName)
- {
- bool bl = false;
- if (classFullName.ToLower().IndexOf("system.") == 0)
- {
- bl = true;
- }
- return bl;
- }
- /// <summary>
- /// 获取实例对象属性的值
- /// </summary>
- /// <param name="model">实例对象</param>
- /// <param name="propertyName">属性名</param>
- /// <returns></returns>
- public static object GetPropertyValue(object model, string propertyName)
- {
- System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
- if (propertyInfo != null)
- {
- object tempValue = propertyInfo.GetValue(model, null);//对应字段值
- return tempValue;
- }
- else
- {
- return null;
- }
- }
- /// <summary>
- /// 设置实例对象属性的值
- /// </summary>
- /// <param name="model">实例对象</param>
- /// <param name="propertyInfo">属性对象</param>
- /// <param name="value">要设置的值</param>
- public static void SetPropertyValue(object model, System.Reflection.PropertyInfo propertyInfo, object value)
- {
- if (propertyInfo == null)
- {
- return;
- }
- Type tempType = propertyInfo.PropertyType;
- if (IsNullable(tempType))
- {
- tempType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
- }
- object tempValue = value;
- if (tempValue == null)
- {
- try
- {
- propertyInfo.SetValue(model, null, null);
- }
- catch { }
- }
- else
- {
- switch (tempType.Name)
- {
- // 空引用。
- case "Empty":
- propertyInfo.SetValue(model, tempValue.ToString(), null);
- break;
- // 常规类型,表示不会由另一个 TypeCode 显式表示的任何引用或值类型。
- case "Object":
- propertyInfo.SetValue(model, tempValue, null);
- break;
- // 数据库空(列)值。
- case "DBNull":
- propertyInfo.SetValue(model, null, null);
- break;
- // 简单类型,表示 true 或 false 的布尔值。
- case "Boolean":
- try
- {
- propertyInfo.SetValue(model, Convert.ToBoolean(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, false, null);
- }
- break;
- //字符
- case "Char":
- propertyInfo.SetValue(model, Convert.ToChar(tempValue), null);
- break;
- // 整型,表示值介于 -128 到 127 之间的有符号 8 位整数。
- case "SByte":
- propertyInfo.SetValue(model, Convert.ToSByte(tempValue), null);
- break;
- // 0 and 255.
- case "Byte":
- propertyInfo.SetValue(model, Convert.ToByte(tempValue), null);
- break;
- // 整型,表示值介于 -32768 到 32767 之间的有符号 16 位整数。
- case "Int16":
- propertyInfo.SetValue(model, Convert.ToInt16(tempValue), null);
- break;
- // 整型,表示值介于 0 到 65535 之间的无符号 16 位整数。
- case "UInt16":
- propertyInfo.SetValue(model, Convert.ToUInt16(tempValue), null);
- break;
- // 整型,表示值介于 -2147483648 到 2147483647 之间的有符号 32 位整数。
- case "Int32":
- try
- {
- propertyInfo.SetValue(model, Convert.ToInt32(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, Convert.ToInt32(0), null);
- }
- break;
- // 整型,表示值介于 0 到 4294967295 之间的无符号 32 位整数。
- case "UInt32":
- propertyInfo.SetValue(model, Convert.ToUInt32(tempValue), null);
- break;
- // 整型,表示值介于 -9223372036854775808 到 9223372036854775807 之间的有符号 64 位整数。
- case "Int64":
- propertyInfo.SetValue(model, Convert.ToInt64(tempValue), null);
- break;
- // 整型,表示值介于 0 到 18446744073709551615 之间的无符号 64 位整数。
- case "UInt64":
- propertyInfo.SetValue(model, Convert.ToUInt64(tempValue), null);
- break;
- // 浮点型,表示从大约 1.5 x 10 -45 到 3.4 x 10 38 且精度为 7 位的值。
- case "Single":
- propertyInfo.SetValue(model, Convert.ToSingle(tempValue), null);
- break;
- // 浮点型,表示从大约 5.0 x 10 -324 到 1.7 x 10 308 且精度为 15 到 16 位的值。
- case "Double":
- try
- {
- propertyInfo.SetValue(model, Convert.ToDouble(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, 0, null);
- }
- break;
- // 简单类型,表示从 1.0 x 10 -28 到大约 7.9 x 10 28 且有效位数为 28 到 29 位的值。
- case "Decimal":
- propertyInfo.SetValue(model, Convert.ToDecimal(tempValue), null);
- break;
- // 表示一个日期和时间值的类型。
- case "DateTime":
- try
- {
- if (tempValue != null)
- {
- propertyInfo.SetValue(model, Convert.ToDateTime(tempValue), null);
- }
- }
- catch
- {
- // propertyInfo.SetValue(model, Convert.ToDateTime("1753-01-01"), null);
- }
- break;
- // 密封类类型,表示 Unicode 字符串。
- case "String":
- propertyInfo.SetValue(model, tempValue.ToString(), null);
- break;
- default:
- string classFullName = tempType.ToString();
- if (!VerificationClassFullNameIsSystem(classFullName))
- {
- try
- {
- Type valueType = tempType.Module.Assembly.GetType(classFullName);
- // object obj = Activator.CreateInstance(type, null);
- tempValue = Activator.CreateInstance(valueType, new object[] { tempValue.ToString() });
- }
- catch { }
- }
- propertyInfo.SetValue(model, tempValue, null);
- break;
- }
- }
- }
- #endregion
- #region 执行简单SQL语句
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="strSQL">SQL语句</param>
- /// <returns>影响的记录数</returns>
- public static int ExecuteSQL(string connectionString, string strSQL)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand(strSQL, connection))
- {
- try
- {
- connection.Open();
- int rows = cmd.ExecuteNonQuery();
- return rows;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- throw e;
- }
- }
- }
- }
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="strSQL">SQL语句</param>
- /// <param name="Timeouts">超时值</param>
- /// <returns></returns>
- public static int ExecuteSQLByTime(string connectionString, string strSQL, int Timeouts)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand(strSQL, connection))
- {
- try
- {
- connection.Open();
- cmd.CommandTimeout = Timeouts;
- int rows = cmd.ExecuteNonQuery();
- return rows;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- throw e;
- }
- }
- }
- }
- /// <summary>
- /// 执行多条SQL语句,实现数据库事务。
- /// </summary>
- /// <param name="listSQL">多条SQL语句</param>
- public static int ExecuteSQLTran(string connectionString, List<String> listSQL)
- {
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- 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 < listSQL.Count; n++)
- {
- string strsql = listSQL[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="strSQL">SQL语句</param>
- /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
- /// <returns>影响的记录数</returns>
- public static int ExecuteSQL(string connectionString, string strSQL, string content)
- {
- System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
- myParameter.Value = content;
- return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
- }
- /// <summary>
- /// 执行带一个存储过程参数的的SQL语句。
- /// </summary>
- /// <param name="strSQL">SQL语句</param>
- /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
- /// <returns>影响的记录数</returns>
- public static object ExecuteSQLGet(string connectionString, string strSQL)
- {
- System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
- myParameter.Value = connectionString;
- return GetSingle(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
- }
- /// <summary>
- /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
- /// </summary>
- /// <param name="strSQL">SQL语句</param>
- /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
- /// <returns>影响的记录数</returns>
- public static int ExecuteSQLInsertImg(string connectionString, string strSQL, byte[] fs)
- {
- System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
- myParameter.Value = fs;
- return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
- }
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>DataSet</returns>
- public static DataSet Query(string connectionString, string strSQL)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- DataSet ds = new DataSet();
- try
- {
- connection.Open();
- SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
- command.Fill(ds, "ds");
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- Log.WriteErrorLog($"错误:{ex.Message},SQL={strSQL}");
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- public static DataSet Query(string connectionString, string strSQL, int Timeout)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- DataSet ds = new DataSet();
- try
- {
- connection.Open();
- SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
- command.SelectCommand.CommandTimeout = Timeout;
- command.Fill(ds, "ds");
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- #endregion
- #region 执行带参数的SQL语句
- /// <summary>
- /// 获取数据库登录用户状态
- /// </summary>
- /// <param name="userName">用户名</param>
- /// <returns>返回 true 为启用 false 为禁用</returns>
- public static bool GetDBUserStatus(string connectionString, string userName = "sa")
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- try
- {
- PrepareCommand(cmd, connection, null, "SELECT is_disabled FROM sys.server_principals WHERE name ='" + userName + "'", null);
- object obj = cmd.ExecuteScalar();
- cmd.Parameters.Clear();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return false;
- }
- else
- {
- return !Convert.ToBoolean(obj);
- }
- }
- catch
- {
- return false;
- }
- }
- }
- }
- /// <summary>
- /// 执行多条SQL语句,实现数据库事务。
- /// </summary>
- /// <param name="listSQL">多条SQL语句</param>
- /// <param name="msg"></param>
- /// <param name="backgroundWorker"></param>
- /// <param name="times"></param>
- /// <returns></returns>
- public static int ExecuteSQLTran(string connectionString, List<string> listSQL, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
- {
- //总计数器
- float sumCount = listSQL.Count;
- //当前计数器
- int currentCount = 0;
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = conn;
- SqlTransaction tx = conn.BeginTransaction();
- cmd.Transaction = tx;
- if (times > 0)
- {
- cmd.CommandTimeout = times;
- }
- try
- {
- int count = 0;
- if (listSQL.Count > 0)
- {
- for (int n = 0; n < listSQL.Count; n++)
- {
- currentCount++;
- string strsql = listSQL[n];
- if (strsql.Trim().Length > 1)
- {
- cmd.CommandText = strsql;
- count += cmd.ExecuteNonQuery();
- }
- if (backgroundWorker != null)
- {
- try
- {
- int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
- backgroundWorker.ReportProgress(currentProgres);
- }
- catch { }
- }
- }
- tx.Commit();
- msg = "成功!";
- return listSQL.Count;
- }
- else
- {
- msg = "失败,错误原因:脚本内容为空!";
- return 0;
- }
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- msg = "失败,错误原因:" + ex.Message;
- tx.Rollback();
- return 0;
- }
- }
- }
- /// <summary>
- /// 执行SQL脚本文件 实现数据库事务。
- /// </summary>
- /// <param name="sqlScript">SQL脚本内容</param>
- /// <param name="msg">返回执行信息</param>
- /// <returns></returns>
- public static bool ExecuteSQLScriptTextTran(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
- {
- bool bl = false;
- List<string> SQLStringList = new List<string>();
- string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- for (int i = 0; i < sqlArray.Length; i++)
- {
- string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
- if (sql.Trim() != "")
- {
- SQLStringList.Add(sql);
- }
- }
- int ret = ExecuteSQLTran(connectionString, SQLStringList, ref msg, backgroundWorker, times);
- if (ret > 0)
- {
- bl = true;
- }
- return bl;
- }
- /// <summary>
- /// 执行SQL脚本文件 实现数据库事务。
- /// </summary>
- /// <param name="sqlScriptFilePath">SQL脚本文件路径</param>
- /// <param name="msg">返回执行信息</param>
- /// <returns></returns>
- public static bool ExecuteSQLScriptFileTran(string connectionString, string sqlScriptFilePath, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
- {
- if (System.IO.File.Exists(sqlScriptFilePath))
- {
- string upgradeDatabaseSql = System.IO.File.ReadAllText(sqlScriptFilePath, System.Text.Encoding.UTF8);
- return ExecuteSQLScriptTextTran(connectionString, upgradeDatabaseSql, ref msg, backgroundWorker, times);
- }
- else
- {
- msg = "要执行的SQL脚本文件不存在!";
- return false;
- }
- }
- /// <summary>
- /// 执行SQL脚本文件
- /// </summary>
- /// <param name="sqlScript">SQL脚本内容</param>
- /// <param name="msg">返回执行信息</param>
- /// <returns></returns>
- public static bool ExecuteSQLScriptFile(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
- {
- bool bl = false;
- string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- //总计数器
- float sumCount = sqlArray.Length;
- //当前计数器
- int currentCount = 0;
- for (int i = 0; i < sqlArray.Length; i++)
- {
- currentCount++;
- string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
- if (sql.Trim() != "")
- {
- System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
- try
- {
- List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
- System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
- if (times > 0)
- {
- ExecuteSQL(connectionString, sql, times, parameters);
- }
- else
- {
- ExecuteSQL(sql, connectionString, parameters);
- }
- msg = "成功!";
- bl = true;
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- msg = "失败,错误原因:" + ex.Message;
- bl = false;
- break;
- }
- }
- if (backgroundWorker != null)
- {
- try
- {
- int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
- backgroundWorker.ReportProgress(currentProgres);
- }
- catch { }
- }
- }
- return bl;
- }
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <returns>影响的记录数</returns>
- public static int ExecuteSQL(string connectionString, string SQLString, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- try
- {
- PrepareCommand(cmd, connection, null, SQLString, cmdParms);
- int rows = cmd.ExecuteNonQuery();
- cmd.Parameters.Clear();
- return rows;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- Log.WriteErrorLog(string.Format("{0}{1}",e.Message, SQLString));
- return -1;
- }
- }
- }
- }
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <returns>影响的记录数</returns>
- public static int ExecuteSQL(string connectionString, string SQLString, int times, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- try
- {
- PrepareCommand(cmd, connection, null, SQLString, cmdParms);
- cmd.CommandTimeout = times;
- int rows = cmd.ExecuteNonQuery();
- cmd.Parameters.Clear();
- return rows;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- throw e;
- }
- }
- }
- }
- /// <summary>
- /// 执行一条计算查询结果语句,返回查询结果(object)。
- /// </summary>
- /// <param name="strSQL">计算查询结果语句</param>
- /// <returns>查询结果(object)</returns>
- public static Object GetSingle(string connectionString, string strSQL)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand(strSQL, 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 (System.Data.SqlClient.SqlException e)
- {
- Log.WriteErrorLog(string.Format("{0}-{1}", strSQL, e.Message));
- throw e;
- }
- }
- }
- }
- public static Object GetSingle(string strSQL, SqlConnection connection)
- {
- using (SqlCommand cmd = new SqlCommand(strSQL, connection))
- {
- try
- {
- if (connection.State != ConnectionState.Open)
- connection.Open();
- object obj = cmd.ExecuteScalar();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return null;
- }
- else
- {
- return obj;
- }
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- connection.Close();
- Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
- throw e;
- }
- }
- }
- public static object GetSingle(string connectionString, string strSQL, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- try
- {
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- object obj = cmd.ExecuteScalar();
- cmd.Parameters.Clear();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return null;
- }
- else
- {
- return obj;
- }
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
- throw e;
- }
- }
- }
- }
- public static object GetSingle(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- try
- {
- if (connection.State != ConnectionState.Open) connection.Open();
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- object obj = cmd.ExecuteScalar();
- cmd.Parameters.Clear();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return null;
- }
- else
- {
- return obj;
- }
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
- throw e;
- }
- }
- }
- /// <summary>
- /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>SqlDataReader</returns>
- public static SqlDataReader ExecuteReader(string connectionString, string strSQL, params SqlParameter[] cmdParms)
- {
- SqlConnection connection = new SqlConnection(connectionString);
- SqlCommand cmd = new SqlCommand();
- try
- {
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- cmd.Parameters.Clear();
- return myReader;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- throw e;
- }
- }
- public static SqlDataReader ExecuteReader(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
- {
- if (connection.State != ConnectionState.Open) connection.Open();
- SqlCommand cmd = new SqlCommand();
- try
- {
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- cmd.Parameters.Clear();
- return myReader;
- }
- catch (System.Data.SqlClient.SqlException e)
- {
- throw e;
- }
- }
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>DataSet</returns>
- public static DataSet MasterQuery(string connectionString, string strSQL, params SqlParameter[] cmdParms)
- {
- return Query(strSQL, connectionString, cmdParms);
- }
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="SQLString">查询语句</param>
- /// <returns>DataSet</returns>
- public static DataSet Query(string connectionString, string strSQL, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand();
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- try
- {
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- }
- public static DataSet Query(SqlConnection connection, string strSQL, params SqlParameter[] cmdParms)
- {
- if (connection.State != ConnectionState.Open) connection.Open();
- SqlCommand cmd = new SqlCommand();
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- try
- {
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>DataSet</returns>
- public static DataSet Query(string connectionString, string strSQL, int times, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand();
- cmd.CommandTimeout = times;
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- try
- {
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- }
- public static DataSet Query(string strSQL, int times, SqlConnection connection, params SqlParameter[] cmdParms)
- {
- if (connection.State != ConnectionState.Open) connection.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.CommandTimeout = times;
- PrepareCommand(cmd, connection, null, strSQL, cmdParms);
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- try
- {
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- }
- catch (System.Data.SqlClient.SqlException ex)
- {
- throw new Exception(ex.Message);
- }
- return ds;
- }
- }
- public static void PublicPrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
- {
- PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
- }
- private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
- {
- if (conn.State != ConnectionState.Open)
- conn.Open();
- cmd.Connection = conn;
- cmd.CommandText = cmdText;
- if (trans != null)
- cmd.Transaction = trans;
- cmd.CommandType = CommandType.Text;//cmdType;
- if (cmdParms != null)
- {
- foreach (SqlParameter parameter in cmdParms)
- {
- if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
- (parameter.Value == null))
- {
- parameter.Value = DBNull.Value;
- }
- cmd.Parameters.Add(parameter);
- }
- }
- }
- #endregion
- #region 存储过程操作
- /// <summary>
- /// 执行存储过程
- /// </summary>
- /// <param name="storedProcName">存储过程名</param>
- /// <param name="parameters">存储过程参数</param>
- /// <param name="tableName">DataSet结果中的表名</param>
- /// <returns>DataSet</returns>
- public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- DataSet dataSet = new DataSet();
- connection.Open();
- SqlDataAdapter sqlDA = new SqlDataAdapter();
- sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
- sqlDA.Fill(dataSet, tableName);
- return dataSet;
- }
- }
- public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName, int Times)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- DataSet dataSet = new DataSet();
- connection.Open();
- SqlDataAdapter sqlDA = new SqlDataAdapter();
- sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
- sqlDA.SelectCommand.CommandTimeout = Times;
- sqlDA.Fill(dataSet, tableName);
- return dataSet;
- }
- }
- /// <summary>
- /// 执行存储过程,返回影响的行数
- /// </summary>
- /// <param name="storedProcName">存储过程名</param>
- /// <param name="parameters">存储过程参数</param>
- /// <param name="rowsAffected">影响的行数</param>
- /// <returns></returns>
- public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
- {
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- int result;
- connection.Open();
- SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
- rowsAffected = command.ExecuteNonQuery();
- result = (int)command.Parameters["ReturnValue"].Value;
- return result;
- }
- }
- /// <summary>
- /// 创建 SqlCommand 对象实例(用来返回一个整数值)
- /// </summary>
- /// <param name="storedProcName">存储过程名</param>
- /// <param name="parameters">存储过程参数</param>
- /// <returns>SqlCommand 对象实例</returns>
- 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;
- }
- /// <summary>
- /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
- /// </summary>
- /// <param name="connection">数据库连接</param>
- /// <param name="storedProcName">存储过程名</param>
- /// <param name="parameters">存储过程参数</param>
- /// <returns>SqlCommand</returns>
- 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)
- {
- // 检查未分配值的输出参数,将其分配以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
- }
- }
|