DbHelper.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. using SXLibrary;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace MOKA_Factory_Tools.Database
  11. {
  12. class DbHelper
  13. {
  14. #region 公共方法
  15. /// <summary>
  16. /// 是否存在该连接对象
  17. /// </summary>
  18. /// <param name="connectionString"></param>
  19. /// <returns></returns>
  20. public static bool IsConnectionExists(string connectionString)
  21. {
  22. using (SqlConnection connection = new SqlConnection(connectionString))
  23. {
  24. try
  25. {
  26. if (connection.State != ConnectionState.Open)
  27. connection.Open();
  28. connection.Close();
  29. return true;
  30. }
  31. catch(Exception e)
  32. {
  33. Log.WriteErrorLog(string.Format("{0}", e.Message));
  34. }
  35. }
  36. return false;
  37. }
  38. /// <summary>
  39. /// 表字段是否存在;
  40. /// </summary>
  41. /// <param name="tableName"></param>
  42. /// <param name="columnName"></param>
  43. /// <returns></returns>
  44. public static bool IsColumnExists(string connectionString, string tableName, string columnName)
  45. {
  46. string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
  47. object res = GetSingle(sql, connectionString);
  48. if (res == null)
  49. {
  50. return false;
  51. }
  52. return Convert.ToInt32(res) > 0;
  53. }
  54. /// <summary>
  55. /// 表是否存在;
  56. /// </summary>
  57. /// <param name="tableName"></param>
  58. /// <returns></returns>
  59. public static bool IsTableExists(string connectionString, string tableName)
  60. {
  61. string strsql = "select count(*) from sysobjects where id = object_id(N'[" + tableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
  62. object obj = GetSingle(strsql, connectionString);
  63. int cmdresult;
  64. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  65. {
  66. cmdresult = 0;
  67. }
  68. else
  69. {
  70. cmdresult = int.Parse(obj.ToString());
  71. }
  72. if (cmdresult == 0)
  73. {
  74. return false;
  75. }
  76. else
  77. {
  78. return true;
  79. }
  80. }
  81. /// <summary>
  82. /// 视图是否存在
  83. /// </summary>
  84. /// <param name="TableName"></param>
  85. /// <returns></returns>
  86. public static bool IsViewsExists(string connectionString, string viewsName)
  87. {
  88. try
  89. {
  90. string strsql = "SELECT count([object_id]) as objCount FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[" + viewsName + "]')";
  91. //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
  92. object obj = GetSingle(strsql, connectionString);
  93. int cmdresult;
  94. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  95. {
  96. cmdresult = 0;
  97. }
  98. else
  99. {
  100. cmdresult = int.Parse(obj.ToString());
  101. }
  102. if (cmdresult == 0)
  103. {
  104. return false;
  105. }
  106. else
  107. {
  108. return true;
  109. }
  110. }
  111. catch
  112. {
  113. }
  114. return false;
  115. }
  116. public static int GetMaxID(string connectionString, string FieldName, string TableName, string strWhere = "")
  117. {
  118. string strsql = "select max(" + FieldName + ")+1 from " + TableName;
  119. if (strWhere.Trim() != "")
  120. {
  121. strsql += (" where 1=1 and (" + strWhere + ")");
  122. }
  123. object obj = GetSingle(connectionString, strsql);
  124. if (obj == null)
  125. {
  126. return 1;
  127. }
  128. else
  129. {
  130. return int.Parse(obj.ToString());
  131. }
  132. }
  133. public static bool Exists(string connectionString, string strSQL)
  134. {
  135. int cmdresult;
  136. object obj = GetSingle(connectionString, strSQL);
  137. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  138. {
  139. cmdresult = 0;
  140. }
  141. else
  142. {
  143. cmdresult = int.Parse(obj.ToString());
  144. }
  145. if (cmdresult == 0)
  146. {
  147. return false;
  148. }
  149. else
  150. {
  151. return true;
  152. }
  153. }
  154. public static bool Exists(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  155. {
  156. object obj = GetSingle(connectionString, strSQL, cmdParms);
  157. int cmdresult;
  158. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  159. {
  160. cmdresult = 0;
  161. }
  162. else
  163. {
  164. cmdresult = int.Parse(obj.ToString());
  165. }
  166. if (cmdresult == 0)
  167. {
  168. return false;
  169. }
  170. else
  171. {
  172. return true;
  173. }
  174. }
  175. /// <summary>
  176. /// 获取时间为"1900-01-01"的日期对象
  177. /// </summary>
  178. /// <returns></returns>
  179. public static DateTime GetNullDateTime()
  180. {
  181. return Convert.ToDateTime("1900-01-01");
  182. }
  183. /// <summary>
  184. /// 全局ID GUID获取19位的唯一数字序列
  185. /// </summary>
  186. /// <returns></returns>
  187. public static long GenerateId()
  188. {
  189. byte[] buffer = Guid.NewGuid().ToByteArray();
  190. return BitConverter.ToInt64(buffer, 0);
  191. }
  192. /// <summary>
  193. /// 返回指定类型是否为允许为null的 Nullable泛型对象
  194. /// </summary>
  195. /// <param name="_type"></param>
  196. /// <returns>是Nullable泛型对象为 true 否则为 false</returns>
  197. public static bool IsNullable(Type _type)
  198. {
  199. bool bl = _type.Name.ToLower().Contains("Nullable".ToLower());
  200. return bl;
  201. }
  202. /// <summary>
  203. /// 验证一个类的完全限定名中是否以“system.”开头
  204. /// </summary>
  205. /// <param name="classFullName"></param>
  206. /// <returns>以“system.”开头为 true 否则为 false </returns>
  207. public static bool VerificationClassFullNameIsSystem(string classFullName)
  208. {
  209. bool bl = false;
  210. if (classFullName.ToLower().IndexOf("system.") == 0)
  211. {
  212. bl = true;
  213. }
  214. return bl;
  215. }
  216. /// <summary>
  217. /// 获取实例对象属性的值
  218. /// </summary>
  219. /// <param name="model">实例对象</param>
  220. /// <param name="propertyName">属性名</param>
  221. /// <returns></returns>
  222. public static object GetPropertyValue(object model, string propertyName)
  223. {
  224. System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
  225. if (propertyInfo != null)
  226. {
  227. object tempValue = propertyInfo.GetValue(model, null);//对应字段值
  228. return tempValue;
  229. }
  230. else
  231. {
  232. return null;
  233. }
  234. }
  235. /// <summary>
  236. /// 设置实例对象属性的值
  237. /// </summary>
  238. /// <param name="model">实例对象</param>
  239. /// <param name="propertyInfo">属性对象</param>
  240. /// <param name="value">要设置的值</param>
  241. public static void SetPropertyValue(object model, System.Reflection.PropertyInfo propertyInfo, object value)
  242. {
  243. if (propertyInfo == null)
  244. {
  245. return;
  246. }
  247. Type tempType = propertyInfo.PropertyType;
  248. if (IsNullable(tempType))
  249. {
  250. tempType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
  251. }
  252. object tempValue = value;
  253. if (tempValue == null)
  254. {
  255. try
  256. {
  257. propertyInfo.SetValue(model, null, null);
  258. }
  259. catch { }
  260. }
  261. else
  262. {
  263. switch (tempType.Name)
  264. {
  265. // 空引用。
  266. case "Empty":
  267. propertyInfo.SetValue(model, tempValue.ToString(), null);
  268. break;
  269. // 常规类型,表示不会由另一个 TypeCode 显式表示的任何引用或值类型。
  270. case "Object":
  271. propertyInfo.SetValue(model, tempValue, null);
  272. break;
  273. // 数据库空(列)值。
  274. case "DBNull":
  275. propertyInfo.SetValue(model, null, null);
  276. break;
  277. // 简单类型,表示 true 或 false 的布尔值。
  278. case "Boolean":
  279. try
  280. {
  281. propertyInfo.SetValue(model, Convert.ToBoolean(tempValue), null);
  282. }
  283. catch
  284. {
  285. propertyInfo.SetValue(model, false, null);
  286. }
  287. break;
  288. //字符
  289. case "Char":
  290. propertyInfo.SetValue(model, Convert.ToChar(tempValue), null);
  291. break;
  292. // 整型,表示值介于 -128 到 127 之间的有符号 8 位整数。
  293. case "SByte":
  294. propertyInfo.SetValue(model, Convert.ToSByte(tempValue), null);
  295. break;
  296. // 0 and 255.
  297. case "Byte":
  298. propertyInfo.SetValue(model, Convert.ToByte(tempValue), null);
  299. break;
  300. // 整型,表示值介于 -32768 到 32767 之间的有符号 16 位整数。
  301. case "Int16":
  302. propertyInfo.SetValue(model, Convert.ToInt16(tempValue), null);
  303. break;
  304. // 整型,表示值介于 0 到 65535 之间的无符号 16 位整数。
  305. case "UInt16":
  306. propertyInfo.SetValue(model, Convert.ToUInt16(tempValue), null);
  307. break;
  308. // 整型,表示值介于 -2147483648 到 2147483647 之间的有符号 32 位整数。
  309. case "Int32":
  310. try
  311. {
  312. propertyInfo.SetValue(model, Convert.ToInt32(tempValue), null);
  313. }
  314. catch
  315. {
  316. propertyInfo.SetValue(model, Convert.ToInt32(0), null);
  317. }
  318. break;
  319. // 整型,表示值介于 0 到 4294967295 之间的无符号 32 位整数。
  320. case "UInt32":
  321. propertyInfo.SetValue(model, Convert.ToUInt32(tempValue), null);
  322. break;
  323. // 整型,表示值介于 -9223372036854775808 到 9223372036854775807 之间的有符号 64 位整数。
  324. case "Int64":
  325. propertyInfo.SetValue(model, Convert.ToInt64(tempValue), null);
  326. break;
  327. // 整型,表示值介于 0 到 18446744073709551615 之间的无符号 64 位整数。
  328. case "UInt64":
  329. propertyInfo.SetValue(model, Convert.ToUInt64(tempValue), null);
  330. break;
  331. // 浮点型,表示从大约 1.5 x 10 -45 到 3.4 x 10 38 且精度为 7 位的值。
  332. case "Single":
  333. propertyInfo.SetValue(model, Convert.ToSingle(tempValue), null);
  334. break;
  335. // 浮点型,表示从大约 5.0 x 10 -324 到 1.7 x 10 308 且精度为 15 到 16 位的值。
  336. case "Double":
  337. try
  338. {
  339. propertyInfo.SetValue(model, Convert.ToDouble(tempValue), null);
  340. }
  341. catch
  342. {
  343. propertyInfo.SetValue(model, 0, null);
  344. }
  345. break;
  346. // 简单类型,表示从 1.0 x 10 -28 到大约 7.9 x 10 28 且有效位数为 28 到 29 位的值。
  347. case "Decimal":
  348. propertyInfo.SetValue(model, Convert.ToDecimal(tempValue), null);
  349. break;
  350. // 表示一个日期和时间值的类型。
  351. case "DateTime":
  352. try
  353. {
  354. if (tempValue != null)
  355. {
  356. propertyInfo.SetValue(model, Convert.ToDateTime(tempValue), null);
  357. }
  358. }
  359. catch
  360. {
  361. // propertyInfo.SetValue(model, Convert.ToDateTime("1753-01-01"), null);
  362. }
  363. break;
  364. // 密封类类型,表示 Unicode 字符串。
  365. case "String":
  366. propertyInfo.SetValue(model, tempValue.ToString(), null);
  367. break;
  368. default:
  369. string classFullName = tempType.ToString();
  370. if (!VerificationClassFullNameIsSystem(classFullName))
  371. {
  372. try
  373. {
  374. Type valueType = tempType.Module.Assembly.GetType(classFullName);
  375. // object obj = Activator.CreateInstance(type, null);
  376. tempValue = Activator.CreateInstance(valueType, new object[] { tempValue.ToString() });
  377. }
  378. catch { }
  379. }
  380. propertyInfo.SetValue(model, tempValue, null);
  381. break;
  382. }
  383. }
  384. }
  385. #endregion
  386. #region 执行简单SQL语句
  387. /// <summary>
  388. /// 执行SQL语句,返回影响的记录数
  389. /// </summary>
  390. /// <param name="strSQL">SQL语句</param>
  391. /// <returns>影响的记录数</returns>
  392. public static int ExecuteSQL(string connectionString, string strSQL)
  393. {
  394. using (SqlConnection connection = new SqlConnection(connectionString))
  395. {
  396. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  397. {
  398. try
  399. {
  400. connection.Open();
  401. int rows = cmd.ExecuteNonQuery();
  402. return rows;
  403. }
  404. catch (System.Data.SqlClient.SqlException e)
  405. {
  406. throw e;
  407. }
  408. }
  409. }
  410. }
  411. /// <summary>
  412. /// 执行SQL语句,返回影响的记录数
  413. /// </summary>
  414. /// <param name="strSQL">SQL语句</param>
  415. /// <param name="Timeouts">超时值</param>
  416. /// <returns></returns>
  417. public static int ExecuteSQLByTime(string connectionString, string strSQL, int Timeouts)
  418. {
  419. using (SqlConnection connection = new SqlConnection(connectionString))
  420. {
  421. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  422. {
  423. try
  424. {
  425. connection.Open();
  426. cmd.CommandTimeout = Timeouts;
  427. int rows = cmd.ExecuteNonQuery();
  428. return rows;
  429. }
  430. catch (System.Data.SqlClient.SqlException e)
  431. {
  432. throw e;
  433. }
  434. }
  435. }
  436. }
  437. /// <summary>
  438. /// 执行多条SQL语句,实现数据库事务。
  439. /// </summary>
  440. /// <param name="listSQL">多条SQL语句</param>
  441. public static int ExecuteSQLTran(string connectionString, List<String> listSQL)
  442. {
  443. using (SqlConnection conn = new SqlConnection(connectionString))
  444. {
  445. conn.Open();
  446. SqlCommand cmd = new SqlCommand();
  447. cmd.Connection = conn;
  448. SqlTransaction tx = conn.BeginTransaction();
  449. cmd.Transaction = tx;
  450. try
  451. {
  452. int count = 0;
  453. for (int n = 0; n < listSQL.Count; n++)
  454. {
  455. string strsql = listSQL[n];
  456. if (strsql.Trim().Length > 1)
  457. {
  458. cmd.CommandText = strsql;
  459. count += cmd.ExecuteNonQuery();
  460. }
  461. }
  462. tx.Commit();
  463. return count;
  464. }
  465. catch
  466. {
  467. tx.Rollback();
  468. return 0;
  469. }
  470. }
  471. }
  472. /// <summary>
  473. /// 执行带一个存储过程参数的的SQL语句。
  474. /// </summary>
  475. /// <param name="strSQL">SQL语句</param>
  476. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  477. /// <returns>影响的记录数</returns>
  478. public static int ExecuteSQL(string connectionString, string strSQL, string content)
  479. {
  480. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
  481. myParameter.Value = content;
  482. return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
  483. }
  484. /// <summary>
  485. /// 执行带一个存储过程参数的的SQL语句。
  486. /// </summary>
  487. /// <param name="strSQL">SQL语句</param>
  488. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  489. /// <returns>影响的记录数</returns>
  490. public static object ExecuteSQLGet(string connectionString, string strSQL)
  491. {
  492. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
  493. myParameter.Value = connectionString;
  494. return GetSingle(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
  495. }
  496. /// <summary>
  497. /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
  498. /// </summary>
  499. /// <param name="strSQL">SQL语句</param>
  500. /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
  501. /// <returns>影响的记录数</returns>
  502. public static int ExecuteSQLInsertImg(string connectionString, string strSQL, byte[] fs)
  503. {
  504. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
  505. myParameter.Value = fs;
  506. return ExecuteSQL(strSQL, connectionString, new System.Data.SqlClient.SqlParameter[] { myParameter });
  507. }
  508. /// <summary>
  509. /// 执行查询语句,返回DataSet
  510. /// </summary>
  511. /// <param name="strSQL">查询语句</param>
  512. /// <returns>DataSet</returns>
  513. public static DataSet Query(string connectionString, string strSQL)
  514. {
  515. using (SqlConnection connection = new SqlConnection(connectionString))
  516. {
  517. DataSet ds = new DataSet();
  518. try
  519. {
  520. connection.Open();
  521. SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
  522. command.Fill(ds, "ds");
  523. }
  524. catch (System.Data.SqlClient.SqlException ex)
  525. {
  526. throw new Exception(ex.Message);
  527. }
  528. return ds;
  529. }
  530. }
  531. public static DataSet Query(string connectionString, string strSQL, int Timeout)
  532. {
  533. using (SqlConnection connection = new SqlConnection(connectionString))
  534. {
  535. DataSet ds = new DataSet();
  536. try
  537. {
  538. connection.Open();
  539. SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
  540. command.SelectCommand.CommandTimeout = Timeout;
  541. command.Fill(ds, "ds");
  542. }
  543. catch (System.Data.SqlClient.SqlException ex)
  544. {
  545. throw new Exception(ex.Message);
  546. }
  547. return ds;
  548. }
  549. }
  550. #endregion
  551. #region 执行带参数的SQL语句
  552. /// <summary>
  553. /// 获取数据库登录用户状态
  554. /// </summary>
  555. /// <param name="userName">用户名</param>
  556. /// <returns>返回 true 为启用 false 为禁用</returns>
  557. public static bool GetDBUserStatus(string connectionString, string userName = "sa")
  558. {
  559. using (SqlConnection connection = new SqlConnection(connectionString))
  560. {
  561. using (SqlCommand cmd = new SqlCommand())
  562. {
  563. try
  564. {
  565. PrepareCommand(cmd, connection, null, "SELECT is_disabled FROM sys.server_principals WHERE name ='" + userName + "'", null);
  566. object obj = cmd.ExecuteScalar();
  567. cmd.Parameters.Clear();
  568. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  569. {
  570. return false;
  571. }
  572. else
  573. {
  574. return !Convert.ToBoolean(obj);
  575. }
  576. }
  577. catch
  578. {
  579. return false;
  580. }
  581. }
  582. }
  583. }
  584. /// <summary>
  585. /// 执行多条SQL语句,实现数据库事务。
  586. /// </summary>
  587. /// <param name="listSQL">多条SQL语句</param>
  588. /// <param name="msg"></param>
  589. /// <param name="backgroundWorker"></param>
  590. /// <param name="times"></param>
  591. /// <returns></returns>
  592. public static int ExecuteSQLTran(string connectionString, List<string> listSQL, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  593. {
  594. //总计数器
  595. float sumCount = listSQL.Count;
  596. //当前计数器
  597. int currentCount = 0;
  598. using (SqlConnection conn = new SqlConnection(connectionString))
  599. {
  600. conn.Open();
  601. SqlCommand cmd = new SqlCommand();
  602. cmd.Connection = conn;
  603. SqlTransaction tx = conn.BeginTransaction();
  604. cmd.Transaction = tx;
  605. if (times > 0)
  606. {
  607. cmd.CommandTimeout = times;
  608. }
  609. try
  610. {
  611. int count = 0;
  612. if (listSQL.Count > 0)
  613. {
  614. for (int n = 0; n < listSQL.Count; n++)
  615. {
  616. currentCount++;
  617. string strsql = listSQL[n];
  618. if (strsql.Trim().Length > 1)
  619. {
  620. cmd.CommandText = strsql;
  621. count += cmd.ExecuteNonQuery();
  622. }
  623. if (backgroundWorker != null)
  624. {
  625. try
  626. {
  627. int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
  628. backgroundWorker.ReportProgress(currentProgres);
  629. }
  630. catch { }
  631. }
  632. }
  633. tx.Commit();
  634. msg = "成功!";
  635. return listSQL.Count;
  636. }
  637. else
  638. {
  639. msg = "失败,错误原因:脚本内容为空!";
  640. return 0;
  641. }
  642. }
  643. catch (System.Data.SqlClient.SqlException ex)
  644. {
  645. msg = "失败,错误原因:" + ex.Message;
  646. tx.Rollback();
  647. return 0;
  648. }
  649. }
  650. }
  651. /// <summary>
  652. /// 执行SQL脚本文件 实现数据库事务。
  653. /// </summary>
  654. /// <param name="sqlScript">SQL脚本内容</param>
  655. /// <param name="msg">返回执行信息</param>
  656. /// <returns></returns>
  657. public static bool ExecuteSQLScriptTextTran(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  658. {
  659. bool bl = false;
  660. List<string> SQLStringList = new List<string>();
  661. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  662. for (int i = 0; i < sqlArray.Length; i++)
  663. {
  664. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  665. if (sql.Trim() != "")
  666. {
  667. SQLStringList.Add(sql);
  668. }
  669. }
  670. int ret = ExecuteSQLTran(connectionString, SQLStringList, ref msg, backgroundWorker, times);
  671. if (ret > 0)
  672. {
  673. bl = true;
  674. }
  675. return bl;
  676. }
  677. /// <summary>
  678. /// 执行SQL脚本文件 实现数据库事务。
  679. /// </summary>
  680. /// <param name="sqlScriptFilePath">SQL脚本文件路径</param>
  681. /// <param name="msg">返回执行信息</param>
  682. /// <returns></returns>
  683. public static bool ExecuteSQLScriptFileTran(string connectionString, string sqlScriptFilePath, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  684. {
  685. if (System.IO.File.Exists(sqlScriptFilePath))
  686. {
  687. string upgradeDatabaseSql = System.IO.File.ReadAllText(sqlScriptFilePath, System.Text.Encoding.UTF8);
  688. return ExecuteSQLScriptTextTran(connectionString, upgradeDatabaseSql, ref msg, backgroundWorker, times);
  689. }
  690. else
  691. {
  692. msg = "要执行的SQL脚本文件不存在!";
  693. return false;
  694. }
  695. }
  696. /// <summary>
  697. /// 执行SQL脚本文件
  698. /// </summary>
  699. /// <param name="sqlScript">SQL脚本内容</param>
  700. /// <param name="msg">返回执行信息</param>
  701. /// <returns></returns>
  702. public static bool ExecuteSQLScriptFile(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  703. {
  704. bool bl = false;
  705. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  706. //总计数器
  707. float sumCount = sqlArray.Length;
  708. //当前计数器
  709. int currentCount = 0;
  710. for (int i = 0; i < sqlArray.Length; i++)
  711. {
  712. currentCount++;
  713. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  714. if (sql.Trim() != "")
  715. {
  716. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  717. try
  718. {
  719. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  720. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  721. if (times > 0)
  722. {
  723. ExecuteSQL(connectionString, sql, times, parameters);
  724. }
  725. else
  726. {
  727. ExecuteSQL(sql, connectionString, parameters);
  728. }
  729. msg = "成功!";
  730. bl = true;
  731. }
  732. catch (System.Data.SqlClient.SqlException ex)
  733. {
  734. msg = "失败,错误原因:" + ex.Message;
  735. bl = false;
  736. break;
  737. }
  738. }
  739. if (backgroundWorker != null)
  740. {
  741. try
  742. {
  743. int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
  744. backgroundWorker.ReportProgress(currentProgres);
  745. }
  746. catch { }
  747. }
  748. }
  749. return bl;
  750. }
  751. /// <summary>
  752. /// 执行SQL语句,返回影响的记录数
  753. /// </summary>
  754. /// <param name="SQLString">SQL语句</param>
  755. /// <returns>影响的记录数</returns>
  756. public static int ExecuteSQL(string connectionString, string SQLString, params SqlParameter[] cmdParms)
  757. {
  758. using (SqlConnection connection = new SqlConnection(connectionString))
  759. {
  760. using (SqlCommand cmd = new SqlCommand())
  761. {
  762. try
  763. {
  764. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  765. int rows = cmd.ExecuteNonQuery();
  766. cmd.Parameters.Clear();
  767. return rows;
  768. }
  769. catch (System.Data.SqlClient.SqlException e)
  770. {
  771. throw e;
  772. }
  773. }
  774. }
  775. }
  776. /// <summary>
  777. /// 执行SQL语句,返回影响的记录数
  778. /// </summary>
  779. /// <param name="SQLString">SQL语句</param>
  780. /// <returns>影响的记录数</returns>
  781. public static int ExecuteSQL(string connectionString, string SQLString, int times, params SqlParameter[] cmdParms)
  782. {
  783. using (SqlConnection connection = new SqlConnection(connectionString))
  784. {
  785. using (SqlCommand cmd = new SqlCommand())
  786. {
  787. try
  788. {
  789. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  790. cmd.CommandTimeout = times;
  791. int rows = cmd.ExecuteNonQuery();
  792. cmd.Parameters.Clear();
  793. return rows;
  794. }
  795. catch (System.Data.SqlClient.SqlException e)
  796. {
  797. throw e;
  798. }
  799. }
  800. }
  801. }
  802. /// <summary>
  803. /// 执行一条计算查询结果语句,返回查询结果(object)。
  804. /// </summary>
  805. /// <param name="strSQL">计算查询结果语句</param>
  806. /// <returns>查询结果(object)</returns>
  807. public static Object GetSingle(string connectionString, string strSQL)
  808. {
  809. using (SqlConnection connection = new SqlConnection(connectionString))
  810. {
  811. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  812. {
  813. try
  814. {
  815. connection.Open();
  816. object obj = cmd.ExecuteScalar();
  817. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  818. {
  819. return null;
  820. }
  821. else
  822. {
  823. return obj;
  824. }
  825. }
  826. catch (System.Data.SqlClient.SqlException e)
  827. {
  828. Log.WriteErrorLog(string.Format("{0}-{1}", strSQL, e.Message));
  829. throw e;
  830. }
  831. }
  832. }
  833. }
  834. public static Object GetSingle(string strSQL, SqlConnection connection)
  835. {
  836. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  837. {
  838. try
  839. {
  840. if (connection.State != ConnectionState.Open)
  841. connection.Open();
  842. object obj = cmd.ExecuteScalar();
  843. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  844. {
  845. return null;
  846. }
  847. else
  848. {
  849. return obj;
  850. }
  851. }
  852. catch (System.Data.SqlClient.SqlException e)
  853. {
  854. connection.Close();
  855. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  856. throw e;
  857. }
  858. }
  859. }
  860. public static object GetSingle(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  861. {
  862. using (SqlConnection connection = new SqlConnection(connectionString))
  863. {
  864. using (SqlCommand cmd = new SqlCommand())
  865. {
  866. try
  867. {
  868. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  869. object obj = cmd.ExecuteScalar();
  870. cmd.Parameters.Clear();
  871. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  872. {
  873. return null;
  874. }
  875. else
  876. {
  877. return obj;
  878. }
  879. }
  880. catch (System.Data.SqlClient.SqlException e)
  881. {
  882. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  883. throw e;
  884. }
  885. }
  886. }
  887. }
  888. public static object GetSingle(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
  889. {
  890. using (SqlCommand cmd = new SqlCommand())
  891. {
  892. try
  893. {
  894. if (connection.State != ConnectionState.Open) connection.Open();
  895. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  896. object obj = cmd.ExecuteScalar();
  897. cmd.Parameters.Clear();
  898. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  899. {
  900. return null;
  901. }
  902. else
  903. {
  904. return obj;
  905. }
  906. }
  907. catch (System.Data.SqlClient.SqlException e)
  908. {
  909. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  910. throw e;
  911. }
  912. }
  913. }
  914. /// <summary>
  915. /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  916. /// </summary>
  917. /// <param name="strSQL">查询语句</param>
  918. /// <returns>SqlDataReader</returns>
  919. public static SqlDataReader ExecuteReader(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  920. {
  921. SqlConnection connection = new SqlConnection(connectionString);
  922. SqlCommand cmd = new SqlCommand();
  923. try
  924. {
  925. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  926. SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  927. cmd.Parameters.Clear();
  928. return myReader;
  929. }
  930. catch (System.Data.SqlClient.SqlException e)
  931. {
  932. throw e;
  933. }
  934. }
  935. public static SqlDataReader ExecuteReader(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
  936. {
  937. if (connection.State != ConnectionState.Open) connection.Open();
  938. SqlCommand cmd = new SqlCommand();
  939. try
  940. {
  941. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  942. SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  943. cmd.Parameters.Clear();
  944. return myReader;
  945. }
  946. catch (System.Data.SqlClient.SqlException e)
  947. {
  948. throw e;
  949. }
  950. }
  951. /// <summary>
  952. /// 执行查询语句,返回DataSet
  953. /// </summary>
  954. /// <param name="strSQL">查询语句</param>
  955. /// <returns>DataSet</returns>
  956. public static DataSet MasterQuery(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  957. {
  958. return Query(strSQL, connectionString, cmdParms);
  959. }
  960. /// <summary>
  961. /// 执行查询语句,返回DataSet
  962. /// </summary>
  963. /// <param name="SQLString">查询语句</param>
  964. /// <returns>DataSet</returns>
  965. public static DataSet Query(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  966. {
  967. using (SqlConnection connection = new SqlConnection(connectionString))
  968. {
  969. SqlCommand cmd = new SqlCommand();
  970. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  971. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  972. {
  973. DataSet ds = new DataSet();
  974. try
  975. {
  976. da.Fill(ds, "ds");
  977. cmd.Parameters.Clear();
  978. }
  979. catch (System.Data.SqlClient.SqlException ex)
  980. {
  981. throw new Exception(ex.Message);
  982. }
  983. return ds;
  984. }
  985. }
  986. }
  987. public static DataSet Query(SqlConnection connection, string strSQL, params SqlParameter[] cmdParms)
  988. {
  989. if (connection.State != ConnectionState.Open) connection.Open();
  990. SqlCommand cmd = new SqlCommand();
  991. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  992. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  993. {
  994. DataSet ds = new DataSet();
  995. try
  996. {
  997. da.Fill(ds, "ds");
  998. cmd.Parameters.Clear();
  999. }
  1000. catch (System.Data.SqlClient.SqlException ex)
  1001. {
  1002. throw new Exception(ex.Message);
  1003. }
  1004. return ds;
  1005. }
  1006. }
  1007. /// <summary>
  1008. /// 执行查询语句,返回DataSet
  1009. /// </summary>
  1010. /// <param name="strSQL">查询语句</param>
  1011. /// <returns>DataSet</returns>
  1012. public static DataSet Query(string connectionString, string strSQL, int times, params SqlParameter[] cmdParms)
  1013. {
  1014. using (SqlConnection connection = new SqlConnection(connectionString))
  1015. {
  1016. SqlCommand cmd = new SqlCommand();
  1017. cmd.CommandTimeout = times;
  1018. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  1019. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1020. {
  1021. DataSet ds = new DataSet();
  1022. try
  1023. {
  1024. da.Fill(ds, "ds");
  1025. cmd.Parameters.Clear();
  1026. }
  1027. catch (System.Data.SqlClient.SqlException ex)
  1028. {
  1029. throw new Exception(ex.Message);
  1030. }
  1031. return ds;
  1032. }
  1033. }
  1034. }
  1035. public static DataSet Query(string strSQL, int times, SqlConnection connection, params SqlParameter[] cmdParms)
  1036. {
  1037. if (connection.State != ConnectionState.Open) connection.Open();
  1038. SqlCommand cmd = new SqlCommand();
  1039. cmd.CommandTimeout = times;
  1040. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  1041. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1042. {
  1043. DataSet ds = new DataSet();
  1044. try
  1045. {
  1046. da.Fill(ds, "ds");
  1047. cmd.Parameters.Clear();
  1048. }
  1049. catch (System.Data.SqlClient.SqlException ex)
  1050. {
  1051. throw new Exception(ex.Message);
  1052. }
  1053. return ds;
  1054. }
  1055. }
  1056. public static void PublicPrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1057. {
  1058. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  1059. }
  1060. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1061. {
  1062. if (conn.State != ConnectionState.Open)
  1063. conn.Open();
  1064. cmd.Connection = conn;
  1065. cmd.CommandText = cmdText;
  1066. if (trans != null)
  1067. cmd.Transaction = trans;
  1068. cmd.CommandType = CommandType.Text;//cmdType;
  1069. if (cmdParms != null)
  1070. {
  1071. foreach (SqlParameter parameter in cmdParms)
  1072. {
  1073. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1074. (parameter.Value == null))
  1075. {
  1076. parameter.Value = DBNull.Value;
  1077. }
  1078. cmd.Parameters.Add(parameter);
  1079. }
  1080. }
  1081. }
  1082. #endregion
  1083. #region 存储过程操作
  1084. /// <summary>
  1085. /// 执行存储过程
  1086. /// </summary>
  1087. /// <param name="storedProcName">存储过程名</param>
  1088. /// <param name="parameters">存储过程参数</param>
  1089. /// <param name="tableName">DataSet结果中的表名</param>
  1090. /// <returns>DataSet</returns>
  1091. public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
  1092. {
  1093. using (SqlConnection connection = new SqlConnection(connectionString))
  1094. {
  1095. DataSet dataSet = new DataSet();
  1096. connection.Open();
  1097. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1098. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1099. sqlDA.Fill(dataSet, tableName);
  1100. return dataSet;
  1101. }
  1102. }
  1103. public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName, int Times)
  1104. {
  1105. using (SqlConnection connection = new SqlConnection(connectionString))
  1106. {
  1107. DataSet dataSet = new DataSet();
  1108. connection.Open();
  1109. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1110. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1111. sqlDA.SelectCommand.CommandTimeout = Times;
  1112. sqlDA.Fill(dataSet, tableName);
  1113. return dataSet;
  1114. }
  1115. }
  1116. /// <summary>
  1117. /// 执行存储过程,返回影响的行数
  1118. /// </summary>
  1119. /// <param name="storedProcName">存储过程名</param>
  1120. /// <param name="parameters">存储过程参数</param>
  1121. /// <param name="rowsAffected">影响的行数</param>
  1122. /// <returns></returns>
  1123. public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
  1124. {
  1125. using (SqlConnection connection = new SqlConnection(connectionString))
  1126. {
  1127. int result;
  1128. connection.Open();
  1129. SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
  1130. rowsAffected = command.ExecuteNonQuery();
  1131. result = (int)command.Parameters["ReturnValue"].Value;
  1132. return result;
  1133. }
  1134. }
  1135. /// <summary>
  1136. /// 创建 SqlCommand 对象实例(用来返回一个整数值)
  1137. /// </summary>
  1138. /// <param name="storedProcName">存储过程名</param>
  1139. /// <param name="parameters">存储过程参数</param>
  1140. /// <returns>SqlCommand 对象实例</returns>
  1141. private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1142. {
  1143. SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
  1144. command.Parameters.Add(new SqlParameter("ReturnValue",
  1145. SqlDbType.Int, 4, ParameterDirection.ReturnValue,
  1146. false, 0, 0, string.Empty, DataRowVersion.Default, null));
  1147. return command;
  1148. }
  1149. /// <summary>
  1150. /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
  1151. /// </summary>
  1152. /// <param name="connection">数据库连接</param>
  1153. /// <param name="storedProcName">存储过程名</param>
  1154. /// <param name="parameters">存储过程参数</param>
  1155. /// <returns>SqlCommand</returns>
  1156. private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1157. {
  1158. SqlCommand command = new SqlCommand(storedProcName, connection);
  1159. command.CommandType = CommandType.StoredProcedure;
  1160. foreach (SqlParameter parameter in parameters)
  1161. {
  1162. if (parameter != null)
  1163. {
  1164. // 检查未分配值的输出参数,将其分配以DBNull.Value.
  1165. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1166. (parameter.Value == null))
  1167. {
  1168. parameter.Value = DBNull.Value;
  1169. }
  1170. command.Parameters.Add(parameter);
  1171. }
  1172. }
  1173. return command;
  1174. }
  1175. #endregion
  1176. }
  1177. }