DbHelper.cs 47 KB

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