DbHelper.cs 47 KB

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