DbHelper.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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. Log.WriteErrorLog($"错误:{ex.Message},SQL={strSQL}");
  527. throw new Exception(ex.Message);
  528. }
  529. return ds;
  530. }
  531. }
  532. public static DataSet Query(string connectionString, string strSQL, int Timeout)
  533. {
  534. using (SqlConnection connection = new SqlConnection(connectionString))
  535. {
  536. DataSet ds = new DataSet();
  537. try
  538. {
  539. connection.Open();
  540. SqlDataAdapter command = new SqlDataAdapter(strSQL, connection);
  541. command.SelectCommand.CommandTimeout = Timeout;
  542. command.Fill(ds, "ds");
  543. }
  544. catch (System.Data.SqlClient.SqlException ex)
  545. {
  546. throw new Exception(ex.Message);
  547. }
  548. return ds;
  549. }
  550. }
  551. #endregion
  552. #region 执行带参数的SQL语句
  553. /// <summary>
  554. /// 获取数据库登录用户状态
  555. /// </summary>
  556. /// <param name="userName">用户名</param>
  557. /// <returns>返回 true 为启用 false 为禁用</returns>
  558. public static bool GetDBUserStatus(string connectionString, string userName = "sa")
  559. {
  560. using (SqlConnection connection = new SqlConnection(connectionString))
  561. {
  562. using (SqlCommand cmd = new SqlCommand())
  563. {
  564. try
  565. {
  566. PrepareCommand(cmd, connection, null, "SELECT is_disabled FROM sys.server_principals WHERE name ='" + userName + "'", null);
  567. object obj = cmd.ExecuteScalar();
  568. cmd.Parameters.Clear();
  569. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  570. {
  571. return false;
  572. }
  573. else
  574. {
  575. return !Convert.ToBoolean(obj);
  576. }
  577. }
  578. catch
  579. {
  580. return false;
  581. }
  582. }
  583. }
  584. }
  585. /// <summary>
  586. /// 执行多条SQL语句,实现数据库事务。
  587. /// </summary>
  588. /// <param name="listSQL">多条SQL语句</param>
  589. /// <param name="msg"></param>
  590. /// <param name="backgroundWorker"></param>
  591. /// <param name="times"></param>
  592. /// <returns></returns>
  593. public static int ExecuteSQLTran(string connectionString, List<string> listSQL, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  594. {
  595. //总计数器
  596. float sumCount = listSQL.Count;
  597. //当前计数器
  598. int currentCount = 0;
  599. using (SqlConnection conn = new SqlConnection(connectionString))
  600. {
  601. conn.Open();
  602. SqlCommand cmd = new SqlCommand();
  603. cmd.Connection = conn;
  604. SqlTransaction tx = conn.BeginTransaction();
  605. cmd.Transaction = tx;
  606. if (times > 0)
  607. {
  608. cmd.CommandTimeout = times;
  609. }
  610. try
  611. {
  612. int count = 0;
  613. if (listSQL.Count > 0)
  614. {
  615. for (int n = 0; n < listSQL.Count; n++)
  616. {
  617. currentCount++;
  618. string strsql = listSQL[n];
  619. if (strsql.Trim().Length > 1)
  620. {
  621. cmd.CommandText = strsql;
  622. count += cmd.ExecuteNonQuery();
  623. }
  624. if (backgroundWorker != null)
  625. {
  626. try
  627. {
  628. int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
  629. backgroundWorker.ReportProgress(currentProgres);
  630. }
  631. catch { }
  632. }
  633. }
  634. tx.Commit();
  635. msg = "成功!";
  636. return listSQL.Count;
  637. }
  638. else
  639. {
  640. msg = "失败,错误原因:脚本内容为空!";
  641. return 0;
  642. }
  643. }
  644. catch (System.Data.SqlClient.SqlException ex)
  645. {
  646. msg = "失败,错误原因:" + ex.Message;
  647. tx.Rollback();
  648. return 0;
  649. }
  650. }
  651. }
  652. /// <summary>
  653. /// 执行SQL脚本文件 实现数据库事务。
  654. /// </summary>
  655. /// <param name="sqlScript">SQL脚本内容</param>
  656. /// <param name="msg">返回执行信息</param>
  657. /// <returns></returns>
  658. public static bool ExecuteSQLScriptTextTran(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  659. {
  660. bool bl = false;
  661. List<string> SQLStringList = new List<string>();
  662. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  663. for (int i = 0; i < sqlArray.Length; i++)
  664. {
  665. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  666. if (sql.Trim() != "")
  667. {
  668. SQLStringList.Add(sql);
  669. }
  670. }
  671. int ret = ExecuteSQLTran(connectionString, SQLStringList, ref msg, backgroundWorker, times);
  672. if (ret > 0)
  673. {
  674. bl = true;
  675. }
  676. return bl;
  677. }
  678. /// <summary>
  679. /// 执行SQL脚本文件 实现数据库事务。
  680. /// </summary>
  681. /// <param name="sqlScriptFilePath">SQL脚本文件路径</param>
  682. /// <param name="msg">返回执行信息</param>
  683. /// <returns></returns>
  684. public static bool ExecuteSQLScriptFileTran(string connectionString, string sqlScriptFilePath, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  685. {
  686. if (System.IO.File.Exists(sqlScriptFilePath))
  687. {
  688. string upgradeDatabaseSql = System.IO.File.ReadAllText(sqlScriptFilePath, System.Text.Encoding.UTF8);
  689. return ExecuteSQLScriptTextTran(connectionString, upgradeDatabaseSql, ref msg, backgroundWorker, times);
  690. }
  691. else
  692. {
  693. msg = "要执行的SQL脚本文件不存在!";
  694. return false;
  695. }
  696. }
  697. /// <summary>
  698. /// 执行SQL脚本文件
  699. /// </summary>
  700. /// <param name="sqlScript">SQL脚本内容</param>
  701. /// <param name="msg">返回执行信息</param>
  702. /// <returns></returns>
  703. public static bool ExecuteSQLScriptFile(string connectionString, string sqlScript, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  704. {
  705. bool bl = false;
  706. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  707. //总计数器
  708. float sumCount = sqlArray.Length;
  709. //当前计数器
  710. int currentCount = 0;
  711. for (int i = 0; i < sqlArray.Length; i++)
  712. {
  713. currentCount++;
  714. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  715. if (sql.Trim() != "")
  716. {
  717. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  718. try
  719. {
  720. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  721. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  722. if (times > 0)
  723. {
  724. ExecuteSQL(connectionString, sql, times, parameters);
  725. }
  726. else
  727. {
  728. ExecuteSQL(sql, connectionString, parameters);
  729. }
  730. msg = "成功!";
  731. bl = true;
  732. }
  733. catch (System.Data.SqlClient.SqlException ex)
  734. {
  735. msg = "失败,错误原因:" + ex.Message;
  736. bl = false;
  737. break;
  738. }
  739. }
  740. if (backgroundWorker != null)
  741. {
  742. try
  743. {
  744. int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
  745. backgroundWorker.ReportProgress(currentProgres);
  746. }
  747. catch { }
  748. }
  749. }
  750. return bl;
  751. }
  752. /// <summary>
  753. /// 执行SQL语句,返回影响的记录数
  754. /// </summary>
  755. /// <param name="SQLString">SQL语句</param>
  756. /// <returns>影响的记录数</returns>
  757. public static int ExecuteSQL(string connectionString, string SQLString, params SqlParameter[] cmdParms)
  758. {
  759. using (SqlConnection connection = new SqlConnection(connectionString))
  760. {
  761. using (SqlCommand cmd = new SqlCommand())
  762. {
  763. try
  764. {
  765. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  766. int rows = cmd.ExecuteNonQuery();
  767. cmd.Parameters.Clear();
  768. return rows;
  769. }
  770. catch (System.Data.SqlClient.SqlException e)
  771. {
  772. Log.WriteErrorLog(string.Format("{0}{1}",e.Message, SQLString));
  773. return -1;
  774. }
  775. }
  776. }
  777. }
  778. /// <summary>
  779. /// 执行SQL语句,返回影响的记录数
  780. /// </summary>
  781. /// <param name="SQLString">SQL语句</param>
  782. /// <returns>影响的记录数</returns>
  783. public static int ExecuteSQL(string connectionString, string SQLString, int times, params SqlParameter[] cmdParms)
  784. {
  785. using (SqlConnection connection = new SqlConnection(connectionString))
  786. {
  787. using (SqlCommand cmd = new SqlCommand())
  788. {
  789. try
  790. {
  791. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  792. cmd.CommandTimeout = times;
  793. int rows = cmd.ExecuteNonQuery();
  794. cmd.Parameters.Clear();
  795. return rows;
  796. }
  797. catch (System.Data.SqlClient.SqlException e)
  798. {
  799. throw e;
  800. }
  801. }
  802. }
  803. }
  804. /// <summary>
  805. /// 执行一条计算查询结果语句,返回查询结果(object)。
  806. /// </summary>
  807. /// <param name="strSQL">计算查询结果语句</param>
  808. /// <returns>查询结果(object)</returns>
  809. public static Object GetSingle(string connectionString, string strSQL)
  810. {
  811. using (SqlConnection connection = new SqlConnection(connectionString))
  812. {
  813. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  814. {
  815. try
  816. {
  817. connection.Open();
  818. object obj = cmd.ExecuteScalar();
  819. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  820. {
  821. return null;
  822. }
  823. else
  824. {
  825. return obj;
  826. }
  827. }
  828. catch (System.Data.SqlClient.SqlException e)
  829. {
  830. Log.WriteErrorLog(string.Format("{0}-{1}", strSQL, e.Message));
  831. throw e;
  832. }
  833. }
  834. }
  835. }
  836. public static Object GetSingle(string strSQL, SqlConnection connection)
  837. {
  838. using (SqlCommand cmd = new SqlCommand(strSQL, connection))
  839. {
  840. try
  841. {
  842. if (connection.State != ConnectionState.Open)
  843. connection.Open();
  844. object obj = cmd.ExecuteScalar();
  845. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  846. {
  847. return null;
  848. }
  849. else
  850. {
  851. return obj;
  852. }
  853. }
  854. catch (System.Data.SqlClient.SqlException e)
  855. {
  856. connection.Close();
  857. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  858. throw e;
  859. }
  860. }
  861. }
  862. public static object GetSingle(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  863. {
  864. using (SqlConnection connection = new SqlConnection(connectionString))
  865. {
  866. using (SqlCommand cmd = new SqlCommand())
  867. {
  868. try
  869. {
  870. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  871. object obj = cmd.ExecuteScalar();
  872. cmd.Parameters.Clear();
  873. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  874. {
  875. return null;
  876. }
  877. else
  878. {
  879. return obj;
  880. }
  881. }
  882. catch (System.Data.SqlClient.SqlException e)
  883. {
  884. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  885. throw e;
  886. }
  887. }
  888. }
  889. }
  890. public static object GetSingle(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
  891. {
  892. using (SqlCommand cmd = new SqlCommand())
  893. {
  894. try
  895. {
  896. if (connection.State != ConnectionState.Open) connection.Open();
  897. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  898. object obj = cmd.ExecuteScalar();
  899. cmd.Parameters.Clear();
  900. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  901. {
  902. return null;
  903. }
  904. else
  905. {
  906. return obj;
  907. }
  908. }
  909. catch (System.Data.SqlClient.SqlException e)
  910. {
  911. Log.WriteErrorLog(string.Format("{0}.{1}", strSQL, e.Message));
  912. throw e;
  913. }
  914. }
  915. }
  916. /// <summary>
  917. /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  918. /// </summary>
  919. /// <param name="strSQL">查询语句</param>
  920. /// <returns>SqlDataReader</returns>
  921. public static SqlDataReader ExecuteReader(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  922. {
  923. SqlConnection connection = new SqlConnection(connectionString);
  924. SqlCommand cmd = new SqlCommand();
  925. try
  926. {
  927. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  928. SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  929. cmd.Parameters.Clear();
  930. return myReader;
  931. }
  932. catch (System.Data.SqlClient.SqlException e)
  933. {
  934. throw e;
  935. }
  936. }
  937. public static SqlDataReader ExecuteReader(string strSQL, SqlConnection connection, params SqlParameter[] cmdParms)
  938. {
  939. if (connection.State != ConnectionState.Open) connection.Open();
  940. SqlCommand cmd = new SqlCommand();
  941. try
  942. {
  943. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  944. SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  945. cmd.Parameters.Clear();
  946. return myReader;
  947. }
  948. catch (System.Data.SqlClient.SqlException e)
  949. {
  950. throw e;
  951. }
  952. }
  953. /// <summary>
  954. /// 执行查询语句,返回DataSet
  955. /// </summary>
  956. /// <param name="strSQL">查询语句</param>
  957. /// <returns>DataSet</returns>
  958. public static DataSet MasterQuery(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  959. {
  960. return Query(strSQL, connectionString, cmdParms);
  961. }
  962. /// <summary>
  963. /// 执行查询语句,返回DataSet
  964. /// </summary>
  965. /// <param name="SQLString">查询语句</param>
  966. /// <returns>DataSet</returns>
  967. public static DataSet Query(string connectionString, string strSQL, params SqlParameter[] cmdParms)
  968. {
  969. using (SqlConnection connection = new SqlConnection(connectionString))
  970. {
  971. SqlCommand cmd = new SqlCommand();
  972. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  973. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  974. {
  975. DataSet ds = new DataSet();
  976. try
  977. {
  978. da.Fill(ds, "ds");
  979. cmd.Parameters.Clear();
  980. }
  981. catch (System.Data.SqlClient.SqlException ex)
  982. {
  983. throw new Exception(ex.Message);
  984. }
  985. return ds;
  986. }
  987. }
  988. }
  989. public static DataSet Query(SqlConnection connection, string strSQL, params SqlParameter[] cmdParms)
  990. {
  991. if (connection.State != ConnectionState.Open) connection.Open();
  992. SqlCommand cmd = new SqlCommand();
  993. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  994. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  995. {
  996. DataSet ds = new DataSet();
  997. try
  998. {
  999. da.Fill(ds, "ds");
  1000. cmd.Parameters.Clear();
  1001. }
  1002. catch (System.Data.SqlClient.SqlException ex)
  1003. {
  1004. throw new Exception(ex.Message);
  1005. }
  1006. return ds;
  1007. }
  1008. }
  1009. /// <summary>
  1010. /// 执行查询语句,返回DataSet
  1011. /// </summary>
  1012. /// <param name="strSQL">查询语句</param>
  1013. /// <returns>DataSet</returns>
  1014. public static DataSet Query(string connectionString, string strSQL, int times, params SqlParameter[] cmdParms)
  1015. {
  1016. using (SqlConnection connection = new SqlConnection(connectionString))
  1017. {
  1018. SqlCommand cmd = new SqlCommand();
  1019. cmd.CommandTimeout = times;
  1020. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  1021. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1022. {
  1023. DataSet ds = new DataSet();
  1024. try
  1025. {
  1026. da.Fill(ds, "ds");
  1027. cmd.Parameters.Clear();
  1028. }
  1029. catch (System.Data.SqlClient.SqlException ex)
  1030. {
  1031. throw new Exception(ex.Message);
  1032. }
  1033. return ds;
  1034. }
  1035. }
  1036. }
  1037. public static DataSet Query(string strSQL, int times, SqlConnection connection, params SqlParameter[] cmdParms)
  1038. {
  1039. if (connection.State != ConnectionState.Open) connection.Open();
  1040. SqlCommand cmd = new SqlCommand();
  1041. cmd.CommandTimeout = times;
  1042. PrepareCommand(cmd, connection, null, strSQL, cmdParms);
  1043. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1044. {
  1045. DataSet ds = new DataSet();
  1046. try
  1047. {
  1048. da.Fill(ds, "ds");
  1049. cmd.Parameters.Clear();
  1050. }
  1051. catch (System.Data.SqlClient.SqlException ex)
  1052. {
  1053. throw new Exception(ex.Message);
  1054. }
  1055. return ds;
  1056. }
  1057. }
  1058. public static void PublicPrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1059. {
  1060. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  1061. }
  1062. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1063. {
  1064. if (conn.State != ConnectionState.Open)
  1065. conn.Open();
  1066. cmd.Connection = conn;
  1067. cmd.CommandText = cmdText;
  1068. if (trans != null)
  1069. cmd.Transaction = trans;
  1070. cmd.CommandType = CommandType.Text;//cmdType;
  1071. if (cmdParms != null)
  1072. {
  1073. foreach (SqlParameter parameter in cmdParms)
  1074. {
  1075. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1076. (parameter.Value == null))
  1077. {
  1078. parameter.Value = DBNull.Value;
  1079. }
  1080. cmd.Parameters.Add(parameter);
  1081. }
  1082. }
  1083. }
  1084. #endregion
  1085. #region 存储过程操作
  1086. /// <summary>
  1087. /// 执行存储过程
  1088. /// </summary>
  1089. /// <param name="storedProcName">存储过程名</param>
  1090. /// <param name="parameters">存储过程参数</param>
  1091. /// <param name="tableName">DataSet结果中的表名</param>
  1092. /// <returns>DataSet</returns>
  1093. public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
  1094. {
  1095. using (SqlConnection connection = new SqlConnection(connectionString))
  1096. {
  1097. DataSet dataSet = new DataSet();
  1098. connection.Open();
  1099. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1100. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1101. sqlDA.Fill(dataSet, tableName);
  1102. return dataSet;
  1103. }
  1104. }
  1105. public static DataSet RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName, int Times)
  1106. {
  1107. using (SqlConnection connection = new SqlConnection(connectionString))
  1108. {
  1109. DataSet dataSet = new DataSet();
  1110. connection.Open();
  1111. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1112. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1113. sqlDA.SelectCommand.CommandTimeout = Times;
  1114. sqlDA.Fill(dataSet, tableName);
  1115. return dataSet;
  1116. }
  1117. }
  1118. /// <summary>
  1119. /// 执行存储过程,返回影响的行数
  1120. /// </summary>
  1121. /// <param name="storedProcName">存储过程名</param>
  1122. /// <param name="parameters">存储过程参数</param>
  1123. /// <param name="rowsAffected">影响的行数</param>
  1124. /// <returns></returns>
  1125. public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
  1126. {
  1127. using (SqlConnection connection = new SqlConnection(connectionString))
  1128. {
  1129. int result;
  1130. connection.Open();
  1131. SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
  1132. rowsAffected = command.ExecuteNonQuery();
  1133. result = (int)command.Parameters["ReturnValue"].Value;
  1134. return result;
  1135. }
  1136. }
  1137. /// <summary>
  1138. /// 创建 SqlCommand 对象实例(用来返回一个整数值)
  1139. /// </summary>
  1140. /// <param name="storedProcName">存储过程名</param>
  1141. /// <param name="parameters">存储过程参数</param>
  1142. /// <returns>SqlCommand 对象实例</returns>
  1143. private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1144. {
  1145. SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
  1146. command.Parameters.Add(new SqlParameter("ReturnValue",
  1147. SqlDbType.Int, 4, ParameterDirection.ReturnValue,
  1148. false, 0, 0, string.Empty, DataRowVersion.Default, null));
  1149. return command;
  1150. }
  1151. /// <summary>
  1152. /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
  1153. /// </summary>
  1154. /// <param name="connection">数据库连接</param>
  1155. /// <param name="storedProcName">存储过程名</param>
  1156. /// <param name="parameters">存储过程参数</param>
  1157. /// <returns>SqlCommand</returns>
  1158. private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1159. {
  1160. SqlCommand command = new SqlCommand(storedProcName, connection);
  1161. command.CommandType = CommandType.StoredProcedure;
  1162. foreach (SqlParameter parameter in parameters)
  1163. {
  1164. if (parameter != null)
  1165. {
  1166. // 检查未分配值的输出参数,将其分配以DBNull.Value.
  1167. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1168. (parameter.Value == null))
  1169. {
  1170. parameter.Value = DBNull.Value;
  1171. }
  1172. command.Parameters.Add(parameter);
  1173. }
  1174. }
  1175. return command;
  1176. }
  1177. #endregion
  1178. }
  1179. }