12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 |
- 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 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(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
- }
- }
|