123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- 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
- {
- }
- }
- 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 strsql = "select max(" + FieldName + ")+1 from " + TableName;
- 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(strSQL, connectionString);
- 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)
- {
- 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)
- {
- throw e;
- }
- }
- }
- }
- /// <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)
- {
- 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();
- 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)
- {
- 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)
- {
- 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
- }
- }
|