Helper_SQLHelper.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. 
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Specialized;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Configuration;
  8. using System.Data.Common;
  9. using System.Collections.Generic;
  10. namespace LYFZ.Helper
  11. {
  12. /// <summary>
  13. /// 数据访问抽象基础类
  14. /// </summary>
  15. public abstract class SQLHelper
  16. {
  17. public SQLHelper()
  18. {
  19. }
  20. #region 公用方法
  21. /// <summary>
  22. /// 检查数据库连接是否正常
  23. /// </summary>
  24. /// <param name="connString"></param>
  25. /// <returns></returns>
  26. public static bool ExistsSqlConn(string connString)
  27. {
  28. bool bl = true;
  29. using (SqlConnection connection = new SqlConnection(connString))
  30. {
  31. try
  32. {
  33. if (connection.State != ConnectionState.Open)
  34. {
  35. connection.Open();
  36. connection.Close();
  37. }
  38. else
  39. {
  40. connection.Close();
  41. }
  42. }
  43. catch
  44. {
  45. bl = false;
  46. }
  47. }
  48. return bl;
  49. }
  50. /// <summary>
  51. /// 判断是否存在某表的某个字段
  52. /// </summary>
  53. /// <param name="tableName">表名称</param>
  54. /// <param name="columnName">列名称</param>
  55. /// <returns>是否存在</returns>
  56. public static bool ColumnExists(string tableName, string columnName, string iGetConn)
  57. {
  58. string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
  59. object res = GetSingle(sql,iGetConn);
  60. if (res == null)
  61. {
  62. return false;
  63. }
  64. return Convert.ToInt32(res) > 0;
  65. }
  66. public static int GetMaxID(string FieldName, string TableName, string iGetConn)
  67. {
  68. string strsql = "select max(" + FieldName + ")+1 from " + TableName;
  69. object obj = GetSingle(strsql,iGetConn);
  70. if (obj == null)
  71. {
  72. return 1;
  73. }
  74. else
  75. {
  76. return int.Parse(obj.ToString());
  77. }
  78. }
  79. public static bool Exists(string strSql, string iGetConn)
  80. {
  81. object obj = GetSingle(strSql,iGetConn);
  82. int cmdresult;
  83. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  84. {
  85. cmdresult = 0;
  86. }
  87. else
  88. {
  89. cmdresult = int.Parse(obj.ToString());
  90. }
  91. if (cmdresult == 0)
  92. {
  93. return false;
  94. }
  95. else
  96. {
  97. return true;
  98. }
  99. }
  100. /// <summary>
  101. /// 表是否存在
  102. /// </summary>
  103. /// <param name="TableName"></param>
  104. /// <returns></returns>
  105. public static bool TabExists(string TableName, string iGetConn)
  106. {
  107. string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
  108. //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
  109. object obj = GetSingle(strsql,iGetConn);
  110. int cmdresult;
  111. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  112. {
  113. cmdresult = 0;
  114. }
  115. else
  116. {
  117. cmdresult = int.Parse(obj.ToString());
  118. }
  119. if (cmdresult == 0)
  120. {
  121. return false;
  122. }
  123. else
  124. {
  125. return true;
  126. }
  127. }
  128. /// <summary>
  129. /// 视图是否存在
  130. /// </summary>
  131. /// <param name="TableName"></param>
  132. /// <returns></returns>
  133. public static bool ViewsExists(string ViewsName, string iGetConn)
  134. {
  135. try
  136. {
  137. string strsql = "SELECT count([object_id]) as objCount FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[" + ViewsName + "]')";
  138. //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
  139. object obj = GetSingle(strsql,iGetConn);
  140. int cmdresult;
  141. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  142. {
  143. cmdresult = 0;
  144. }
  145. else
  146. {
  147. cmdresult = int.Parse(obj.ToString());
  148. }
  149. if (cmdresult == 0)
  150. {
  151. return false;
  152. }
  153. else
  154. {
  155. return true;
  156. }
  157. }
  158. catch { return false; }
  159. }
  160. public static bool Exists(string strSql, string iGetConn, params SqlParameter[] cmdParms)
  161. {
  162. object obj = GetSingle(strSql,iGetConn, cmdParms);
  163. int cmdresult;
  164. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  165. {
  166. cmdresult = 0;
  167. }
  168. else
  169. {
  170. cmdresult = int.Parse(obj.ToString());
  171. }
  172. if (cmdresult == 0)
  173. {
  174. return false;
  175. }
  176. else
  177. {
  178. return true;
  179. }
  180. }
  181. #endregion
  182. #region 执行简单SQL语句
  183. /// <summary>
  184. /// 执行SQL语句,返回影响的记录数
  185. /// </summary>
  186. /// <param name="SQLString">SQL语句</param>
  187. /// <returns>影响的记录数</returns>
  188. public static int ExecuteSql(string SQLString, string iGetConn)
  189. {
  190. using (SqlConnection connection = new SqlConnection(iGetConn))
  191. {
  192. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  193. {
  194. try
  195. {
  196. connection.Open();
  197. int rows = cmd.ExecuteNonQuery();
  198. return rows;
  199. }
  200. catch (System.Data.SqlClient.SqlException e)
  201. {
  202. connection.Close();
  203. throw e;
  204. }
  205. }
  206. }
  207. }
  208. public static int ExecuteSqlByTime(string SQLString, int Times, string iGetConn)
  209. {
  210. using (SqlConnection connection = new SqlConnection(iGetConn))
  211. {
  212. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  213. {
  214. try
  215. {
  216. connection.Open();
  217. cmd.CommandTimeout = Times;
  218. int rows = cmd.ExecuteNonQuery();
  219. return rows;
  220. }
  221. catch (System.Data.SqlClient.SqlException e)
  222. {
  223. connection.Close();
  224. throw e;
  225. }
  226. }
  227. }
  228. }
  229. /// <summary>
  230. /// 执行多条SQL语句,实现数据库事务。
  231. /// </summary>
  232. /// <param name="SQLStringList">多条SQL语句</param>
  233. public static int ExecuteSqlTran(List<String> SQLStringList, string iGetConn)
  234. {
  235. using (SqlConnection conn = new SqlConnection(iGetConn))
  236. {
  237. conn.Open();
  238. SqlCommand cmd = new SqlCommand();
  239. cmd.Connection = conn;
  240. SqlTransaction tx = conn.BeginTransaction();
  241. cmd.Transaction = tx;
  242. try
  243. {
  244. int count = 0;
  245. for (int n = 0; n < SQLStringList.Count; n++)
  246. {
  247. string strsql = SQLStringList[n];
  248. if (strsql.Trim().Length > 1)
  249. {
  250. cmd.CommandText = strsql;
  251. count += cmd.ExecuteNonQuery();
  252. }
  253. }
  254. tx.Commit();
  255. return count;
  256. }
  257. catch
  258. {
  259. tx.Rollback();
  260. return 0;
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// 执行带一个存储过程参数的的SQL语句。
  266. /// </summary>
  267. /// <param name="SQLString">SQL语句</param>
  268. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  269. /// <returns>影响的记录数</returns>
  270. public static int ExecuteSql(string SQLString, string content, string iGetConn)
  271. {
  272. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
  273. myParameter.Value = content;
  274. return ExecuteSql(SQLString,iGetConn, new System.Data.SqlClient.SqlParameter[] { myParameter });
  275. }
  276. /// <summary>
  277. /// 执行带一个存储过程参数的的SQL语句。
  278. /// </summary>
  279. /// <param name="SQLString">SQL语句</param>
  280. /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
  281. /// <returns>影响的记录数</returns>
  282. public static object ExecuteSqlGet(string SQLString, string content, string iGetConn)
  283. {
  284. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
  285. myParameter.Value = content;
  286. return GetSingle(SQLString,iGetConn, new System.Data.SqlClient.SqlParameter[] { myParameter });
  287. }
  288. /// <summary>
  289. /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
  290. /// </summary>
  291. /// <param name="strSQL">SQL语句</param>
  292. /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
  293. /// <returns>影响的记录数</returns>
  294. public static int ExecuteSqlInsertImg(string strSQL, byte[] fs, string iGetConn)
  295. {
  296. System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
  297. myParameter.Value = fs;
  298. return ExecuteSql(strSQL,iGetConn, new System.Data.SqlClient.SqlParameter[] { myParameter });
  299. }
  300. /// <summary>
  301. /// 执行一条计算查询结果语句,返回查询结果(object)。
  302. /// </summary>
  303. /// <param name="SQLString">计算查询结果语句</param>
  304. /// <returns>查询结果(object)</returns>
  305. public static object GetSingle(string SQLString,string connString)
  306. {
  307. using (SqlConnection connection = new SqlConnection(connString))
  308. {
  309. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  310. {
  311. try
  312. {
  313. connection.Open();
  314. object obj = cmd.ExecuteScalar();
  315. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  316. {
  317. return null;
  318. }
  319. else
  320. {
  321. return obj;
  322. }
  323. }
  324. catch (System.Data.SqlClient.SqlException e)
  325. {
  326. connection.Close();
  327. throw e;
  328. }
  329. }
  330. }
  331. }
  332. public static object GetSingle(string SQLString, int Times, string iGetConn)
  333. {
  334. using (SqlConnection connection = new SqlConnection(iGetConn))
  335. {
  336. using (SqlCommand cmd = new SqlCommand(SQLString, connection))
  337. {
  338. try
  339. {
  340. connection.Open();
  341. cmd.CommandTimeout = Times;
  342. object obj = cmd.ExecuteScalar();
  343. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  344. {
  345. return null;
  346. }
  347. else
  348. {
  349. return obj;
  350. }
  351. }
  352. catch (System.Data.SqlClient.SqlException e)
  353. {
  354. connection.Close();
  355. throw e;
  356. }
  357. }
  358. }
  359. }
  360. ///// <summary>
  361. ///// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  362. ///// </summary>
  363. ///// <param name="strSQL">查询语句</param>
  364. ///// <returns>SqlDataReader</returns>
  365. //public static SqlDataReader ExecuteReader(string strSQL)
  366. //{
  367. // SqlConnection connection = new SqlConnection(GetConnectionString.iGetConn);
  368. // SqlCommand cmd = new SqlCommand(strSQL, connection);
  369. // try
  370. // {
  371. // connection.Open();
  372. // SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  373. // return myReader;
  374. // }
  375. // catch (System.Data.SqlClient.SqlException e)
  376. // {
  377. // throw e;
  378. // }
  379. //}
  380. /// <summary>
  381. /// 执行查询语句,返回DataSet
  382. /// </summary>
  383. /// <param name="SQLString">查询语句</param>
  384. /// <returns>DataSet</returns>
  385. public static DataSet Query(string SQLString, string iGetConn)
  386. {
  387. using (SqlConnection connection = new SqlConnection(iGetConn))
  388. {
  389. DataSet ds = new DataSet();
  390. try
  391. {
  392. connection.Open();
  393. SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
  394. command.Fill(ds, "ds");
  395. }
  396. catch (System.Data.SqlClient.SqlException ex)
  397. {
  398. throw new Exception(ex.Message);
  399. }
  400. return ds;
  401. }
  402. }
  403. public static DataSet Query(string SQLString, int Times, string iGetConn)
  404. {
  405. using (SqlConnection connection = new SqlConnection(iGetConn))
  406. {
  407. DataSet ds = new DataSet();
  408. try
  409. {
  410. connection.Open();
  411. SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
  412. command.SelectCommand.CommandTimeout = Times;
  413. command.Fill(ds, "ds");
  414. }
  415. catch (System.Data.SqlClient.SqlException ex)
  416. {
  417. throw new Exception(ex.Message);
  418. }
  419. return ds;
  420. }
  421. }
  422. #endregion
  423. #region 执行带参数的SQL语句
  424. public static string dataBaseServer="127.0.0.1";
  425. public static string baseUser="sa";
  426. public static string basePass="1234";
  427. public static int port=0;
  428. /// <summary>
  429. /// 获取Master数据库连接串
  430. /// </summary>
  431. /// <returns></returns>
  432. public static string GetMasterConnString()
  433. {
  434. string vDataBaseServer = dataBaseServer;
  435. if (port != 0)
  436. {
  437. vDataBaseServer = vDataBaseServer + "," + port;
  438. }
  439. string connString = "Data Source=" + vDataBaseServer + ";Initial Catalog=master;User ID=" + baseUser + ";Password=" + basePass+ "";
  440. return connString;
  441. }
  442. static string _WindowsDataBaseServer = "127.0.0.1";
  443. /// <summary>
  444. /// windows 身份验证连接数据库时的服务器地址 如果有端口号 请加上端口号
  445. /// </summary>
  446. public static string WindowsDataBaseServer
  447. {
  448. get { return SQLHelper._WindowsDataBaseServer; }
  449. set { SQLHelper._WindowsDataBaseServer = value; }
  450. }
  451. /// <summary>
  452. /// 获取Master数据库的windows 身份验证连接串
  453. /// </summary>
  454. /// <returns></returns>
  455. public static string GetWindowsMasterConnString()
  456. {
  457. string vDataBaseServer = WindowsDataBaseServer;
  458. if (port != 0)
  459. {
  460. vDataBaseServer = vDataBaseServer + "," + port;
  461. }
  462. return "server=" + vDataBaseServer + ";database=master;Trusted_Connection=SSPI";
  463. }
  464. /// <summary>
  465. /// 数据库用户管理
  466. /// </summary>
  467. /// <param name="userName">用户名</param>
  468. /// <param name="isDisable">是否禁用 true 为禁用 false 为启用</param>
  469. /// <returns></returns>
  470. public static string DBUserManagement(string userName = "sa", bool isDisable = true)
  471. {
  472. string ret = "操作失败";
  473. try
  474. {
  475. if (isDisable)
  476. {
  477. ExecuteSqlWindowsToMaster("ALTER LOGIN [" + userName + "] DISABLE", null);
  478. ret = "用户禁用成功";
  479. }
  480. else
  481. {
  482. ExecuteSqlWindowsToMaster("ALTER LOGIN [" + userName + "] ENABLE", null);
  483. ret = "用户启用成功";
  484. }
  485. }
  486. catch (System.Data.SqlClient.SqlException e)
  487. {
  488. ret = "操作失败,原因:" + e.Message;
  489. }
  490. return ret;
  491. }
  492. /// <summary>
  493. /// 创建数据库登录用户
  494. /// </summary>
  495. /// <param name="userName">用户名</param>
  496. /// <param name="password">密码</param>
  497. /// <returns></returns>
  498. public static string CreateDBUser(string userName, string password)
  499. {
  500. string ret = "创建成功";
  501. try
  502. {
  503. System.Text.StringBuilder RestoreSql = new System.Text.StringBuilder();
  504. RestoreSql.Append("IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'" + userName + "')\r\n");
  505. RestoreSql.Append("DROP LOGIN [" + userName + "]\r\n");
  506. RestoreSql.Append("CREATE LOGIN [" + userName + "] WITH PASSWORD=N'" + password + "', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON\r\n");
  507. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'bulkadmin'\r\n");
  508. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'dbcreator'\r\n");
  509. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'diskadmin'\r\n");
  510. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'processadmin'\r\n");
  511. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'securityadmin'\r\n");
  512. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'serveradmin'\r\n");
  513. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'setupadmin'\r\n");
  514. RestoreSql.Append("EXEC master..sp_addsrvrolemember @loginame = N'" + userName + "', @rolename = N'sysadmin'\r\n");
  515. ExecuteSqlWindowsToMaster(RestoreSql.ToString(),null);
  516. }
  517. catch (System.Data.SqlClient.SqlException e)
  518. {
  519. ret = "用户创建失败,原因:"+e.Message;
  520. }
  521. return ret;
  522. }
  523. /// <summary>
  524. /// 删除数据库登录用户
  525. /// </summary>
  526. /// <param name="userName">用户名</param>
  527. /// <returns></returns>
  528. public static string DeleteDBUser(string userName)
  529. {
  530. string ret = "删除成功";
  531. try
  532. {
  533. System.Text.StringBuilder RestoreSql = new System.Text.StringBuilder();
  534. RestoreSql.Append("IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'" + userName + "')\r\n");
  535. RestoreSql.Append("ALTER LOGIN [" + userName + "] DISABLE\r\n");
  536. RestoreSql.Append("IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'" + userName + "')\r\n");
  537. RestoreSql.Append("DROP LOGIN [" + userName + "]\r\n");
  538. ExecuteSqlWindowsToMaster(RestoreSql.ToString(), null);
  539. }
  540. catch (System.Data.SqlClient.SqlException e)
  541. {
  542. ret = "用户删除失败,原因:" + e.Message;
  543. }
  544. return ret;
  545. }
  546. /// <summary>
  547. /// 获取数据库登录用户状态
  548. /// </summary>
  549. /// <param name="userName">用户名</param>
  550. /// <returns>返回 true 为启用 false 为禁用</returns>
  551. public static bool GetDBUserStatus(string userName="sa")
  552. {
  553. string connString = GetWindowsMasterConnString();
  554. using (SqlConnection connection = new SqlConnection(connString))
  555. {
  556. using (SqlCommand cmd = new SqlCommand())
  557. {
  558. try
  559. {
  560. PrepareCommand(cmd, connection, null, "SELECT is_disabled FROM sys.server_principals WHERE name ='" + userName + "'", null);
  561. object obj = cmd.ExecuteScalar();
  562. cmd.Parameters.Clear();
  563. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  564. {
  565. return false;
  566. }
  567. else
  568. {
  569. return !Convert.ToBoolean(obj);
  570. }
  571. }
  572. catch
  573. {
  574. return false;
  575. }
  576. }
  577. }
  578. }
  579. /// <summary>
  580. /// windows 身份验证连接Master系统数据库,并执行SQL语句,返回影响的记录数
  581. /// </summary>
  582. /// <param name="SQLString">SQL语句</param>
  583. /// <returns>影响的记录数</returns>
  584. public static int ExecuteSqlWindowsToMaster(string SQLString, params System.Data.SqlClient.SqlParameter[] cmdParms)
  585. {
  586. string connString = GetWindowsMasterConnString();
  587. return ExecuteSql(SQLString, connString, cmdParms);
  588. }
  589. /// <summary>
  590. /// 检查数据库是否存在
  591. /// </summary>
  592. /// <param name="databaseName">数据库名</param>
  593. /// <returns></returns>
  594. public static bool IsDatabaseExists(string databaseName)
  595. {
  596. string dbFilePath="";
  597. return IsDatabaseExists(databaseName, out dbFilePath);
  598. }
  599. /// <summary>
  600. /// 检查数据库是否存在
  601. /// </summary>
  602. /// <param name="databaseName">数据库名</param>
  603. /// <param name="dbFilePath">返数据库文件所在完全路径</param>
  604. /// <returns></returns>
  605. public static bool IsDatabaseExists(string databaseName,out string dbFilePath)
  606. {
  607. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  608. parameterlist.Add(new System.Data.SqlClient.SqlParameter("@databaseName", databaseName));
  609. string sql = "select dbid,name,filename From sysdatabases WHERE NAME=@databaseName";
  610. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  611. // System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  612. dbFilePath = "";
  613. try
  614. {
  615. DataSet ds = LYFZ.Helper.SQLHelper.MasterQuery(sql, parameters);
  616. if (ds.Tables[0].Rows.Count > 0)
  617. {
  618. dbFilePath = ds.Tables[0].Rows[0]["filename"].ToString();
  619. return true;
  620. }
  621. else { return false; }
  622. }
  623. catch
  624. {
  625. return false;
  626. }
  627. }
  628. /// <summary>
  629. /// 强制断开数据库连接
  630. /// </summary>
  631. /// <param name="databaseName"></param>
  632. /// <returns></returns>
  633. public static bool ForcedDisconnect(string databaseName)
  634. {
  635. //LYFZ.Helper.GetConnectionString conn = new Helper.GetConnectionString();
  636. //conn.GetConnInfo();
  637. System.Text.StringBuilder RestoreSql = new System.Text.StringBuilder();
  638. RestoreSql.Append("/* 结束所有对当前数据库的连接 */\r\n");
  639. RestoreSql.Append("if exists(select 1 from sys.sysprocesses where dbid=db_id(@databaseName)) begin\r\n");
  640. RestoreSql.Append("declare #cs_spid cursor -- 声明游标\r\n");
  641. RestoreSql.Append("for\r\n");
  642. RestoreSql.Append("select #cs_spid=convert(varchar,spid) from sys.sysprocesses where dbid=db_id(@databaseName)\r\n");
  643. RestoreSql.Append("open #cs_spid\r\n");
  644. RestoreSql.Append("declare @spid varchar(20)\r\n");
  645. RestoreSql.Append("fetch next from #cs_spid into @spid -- 赋值并前进到下一条\r\n");
  646. RestoreSql.Append("while(@@fetch_status=0) begin -- 在fetch失败前执行\r\n");
  647. RestoreSql.Append("exec ('kill '+@spid) -- 结束对操作库的连接(exec执行SQL语句1)\r\n");
  648. RestoreSql.Append("fetch next from #cs_spid into @spid\r\n");
  649. RestoreSql.Append("end\r\n");
  650. RestoreSql.Append("close #cs_spid\r\n");
  651. RestoreSql.Append("deallocate #cs_spid -- 释放游标\r\n");
  652. RestoreSql.Append("end");
  653. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  654. parameterlist.Add(new System.Data.SqlClient.SqlParameter("@databaseName", databaseName));
  655. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  656. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  657. try
  658. {
  659. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(RestoreSql.ToString(), parameters);
  660. return true;
  661. }
  662. catch
  663. {
  664. return false;
  665. }
  666. }
  667. /// <summary>
  668. /// 分离数据库
  669. /// </summary>
  670. /// <param name="databaseName"></param>
  671. /// <returns></returns>
  672. public static bool DetachDatabase(string databaseName)
  673. {
  674. bool bl = false;
  675. if (IsDatabaseExists(databaseName))
  676. {
  677. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  678. parameterlist.Add(new System.Data.SqlClient.SqlParameter("@databaseName", databaseName));
  679. string sql = "EXEC master.dbo.sp_detach_db @dbname = @databaseName";
  680. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  681. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  682. try
  683. {
  684. LYFZ.Helper.SQLHelper.ForcedDisconnect(databaseName);
  685. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(sql.ToString(), parameters);
  686. if (!IsDatabaseExists(databaseName))
  687. {
  688. bl = true;
  689. }
  690. else
  691. {
  692. bl = false;
  693. }
  694. }
  695. catch
  696. {
  697. bl = false;
  698. }
  699. }
  700. return bl;
  701. }
  702. /// <summary>
  703. ///创建数据库用户
  704. /// </summary>
  705. /// <param name="userName"></param>
  706. /// <param name="password"></param>
  707. /// <param name="databaseName"></param>
  708. /// <returns></returns>
  709. public static bool CreateDataBaseUser(string userName,string password,string databaseName,ref string msg)
  710. {
  711. bool bl = false;
  712. if (IsDatabaseExists(databaseName))
  713. {
  714. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("“" + userName + "”“" + password + "”“" + databaseName + "”开始创建数据库用户...");
  715. System.Text.StringBuilder sql = new System.Text.StringBuilder();
  716. sql.Append(String.Format("IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'{0}')\r\n", userName));
  717. sql.Append(String.Format("DROP LOGIN [{0}]\r\n", userName));
  718. sql.Append(String.Format("CREATE LOGIN [{0}] WITH PASSWORD=N'{1}', DEFAULT_DATABASE=[{2}], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON\r\n", userName, password, databaseName));
  719. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  720. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  721. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  722. try
  723. {
  724. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("创建数据库用户SQL:" + sql);
  725. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(sql.ToString(), parameters);
  726. if (IsDataBaseUserExists(userName))
  727. {
  728. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("创建数据库用户OK:");
  729. bl = true;
  730. }
  731. else
  732. {
  733. bl = false;
  734. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("创建数据库用户false:");
  735. }
  736. }
  737. catch (Exception ex)
  738. {
  739. msg = ex.Message;
  740. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("创建数据库用户出错:" + msg);
  741. bl = false;
  742. }
  743. }
  744. else {
  745. msg = "没有找到名为“" + databaseName + "”的数据库";
  746. // HPSocketCS.Extended.SystemFileLogs.WriteLogs("创建数据库用户失败" + msg);
  747. }
  748. return bl;
  749. }
  750. /// <summary>
  751. /// 检查数据库用户是否存在
  752. /// </summary>
  753. /// <param name="userName"></param>
  754. /// <returns></returns>
  755. public static bool IsDataBaseUserExists(string userName)
  756. {
  757. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  758. string sql = String.Format("SELECT * FROM sys.server_principals WHERE name = N'{0}'", userName);
  759. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  760. try
  761. {
  762. DataSet ds = LYFZ.Helper.SQLHelper.MasterQuery(sql, parameters);
  763. if (ds.Tables[0].Rows.Count > 0)
  764. {
  765. return true;
  766. }
  767. else
  768. {
  769. return false;
  770. }
  771. }
  772. catch
  773. {
  774. return false;
  775. }
  776. }
  777. /// <summary>
  778. /// 设置数据库用户权限
  779. /// </summary>
  780. /// <param name="userName"></param>
  781. /// <param name="databaseName"></param>
  782. /// <returns></returns>
  783. public static bool SetDataBaseUserPermissions(string userName, string databaseName,ref string msg)
  784. {
  785. bool bl = false;
  786. if (IsDatabaseExists(databaseName) && IsDataBaseUserExists(userName))
  787. {
  788. System.Text.StringBuilder sql = new System.Text.StringBuilder();
  789. sql.Append(String.Format("USE [{0}]\r\n", databaseName));
  790. sql.Append(String.Format("IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'{0}')\r\n", userName));
  791. sql.Append(String.Format("DROP USER [{0}]\r\n", userName));
  792. sql.Append(String.Format("CREATE USER [{0}] FOR LOGIN [{0}] WITH DEFAULT_SCHEMA=[dbo]\r\n", userName));
  793. sql.Append(String.Format("EXEC sp_addrolemember N'db_backupoperator', N'{0}'\r\n", userName));
  794. sql.Append(String.Format("EXEC sp_addrolemember N'db_datareader', N'{0}'\r\n", userName));
  795. sql.Append(String.Format("EXEC sp_addrolemember N'db_datawriter', N'{0}'\r\n", userName));
  796. sql.Append(String.Format("EXEC sp_addrolemember N'db_ddladmin', N'{0}'\r\n", userName));
  797. sql.Append(String.Format("EXEC sp_addrolemember N'db_owner', N'{0}'\r\n", userName));
  798. sql.Append(String.Format("EXEC sp_addrolemember N'db_securityadmin', N'{0}'\r\n", userName));
  799. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  800. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  801. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  802. try
  803. {
  804. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(sql.ToString(), parameters);
  805. bl = true;
  806. }
  807. catch(Exception ex)
  808. {
  809. msg = ex.Message;
  810. bl = false;
  811. }
  812. }
  813. return bl;
  814. }
  815. /// <summary>
  816. /// 附加数据库
  817. /// </summary>
  818. /// <param name="databaseFilePath"></param>
  819. /// <param name="databaseLogsFilePath"></param>
  820. /// <param name="databaseName"></param>
  821. /// <returns></returns>
  822. public static bool AddDatabase(string databaseFilePath, string databaseLogsFilePath, string databaseName)
  823. {
  824. bool bl = false;
  825. if (!IsDatabaseExists(databaseName))
  826. {
  827. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  828. string sql = "CREATE DATABASE [" + databaseName + "] ON ( FILENAME ='" + databaseFilePath + "' ),( FILENAME ='" + databaseLogsFilePath + "' ) FOR ATTACH";
  829. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  830. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  831. try
  832. {
  833. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(sql.ToString(), parameters);
  834. if (IsDatabaseExists(databaseName))
  835. {
  836. DatabaseLogRecoveryMode(databaseName);
  837. bl = true;
  838. }
  839. else
  840. {
  841. bl = false;
  842. }
  843. }
  844. catch
  845. {
  846. bl = false;
  847. }
  848. }
  849. else
  850. {
  851. bl = true;
  852. }
  853. return bl;
  854. }
  855. /// <summary>
  856. /// 数据库日志恢复模式
  857. /// </summary>
  858. /// <param name="databaseName"></param>
  859. /// <param name="mode"></param>
  860. public static void DatabaseLogRecoveryMode(string databaseName, string mode = "SIMPLE")
  861. {
  862. if (IsDatabaseExists(databaseName))
  863. {
  864. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  865. parameterlist.Add(new System.Data.SqlClient.SqlParameter("@databaseName", databaseName));
  866. parameterlist.Add(new System.Data.SqlClient.SqlParameter("@SIMPLE", databaseName));
  867. string sql = "ALTER DATABASE @databaseName SET RECOVERY @SIMPLE ;";
  868. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  869. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  870. try
  871. {
  872. LYFZ.Helper.SQLHelper.ExecuteSqlToMaster(sql.ToString(), parameters);
  873. }
  874. catch
  875. {
  876. }
  877. }
  878. }
  879. /// <summary>
  880. /// 连接Master系统数据库,并执行SQL语句,返回影响的记录数
  881. /// </summary>
  882. /// <param name="SQLString">SQL语句</param>
  883. /// <returns>影响的记录数</returns>
  884. public static int ExecuteSqlToMaster(string SQLString, params System.Data.SqlClient.SqlParameter[] cmdParms)
  885. {
  886. string connString =GetWindowsMasterConnString();
  887. return ExecuteSql(SQLString, connString, cmdParms);
  888. }
  889. /// <summary>
  890. /// 执行多条SQL语句,实现数据库事务。
  891. /// </summary>
  892. /// <param name="SQLStringList">多条SQL语句</param>
  893. /// <param name="msg"></param>
  894. /// <param name="backgroundWorker"></param>
  895. /// <param name="times"></param>
  896. /// <returns></returns>
  897. public static int ExecuteSqlTran(List<string> SQLStringList, string iGetConn, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  898. {
  899. //总计数器
  900. float sumCount = SQLStringList.Count;
  901. //当前计数器
  902. int currentCount = 0;
  903. using (SqlConnection conn = new SqlConnection(iGetConn))
  904. {
  905. conn.Open();
  906. SqlCommand cmd = new SqlCommand();
  907. cmd.Connection = conn;
  908. SqlTransaction tx = conn.BeginTransaction();
  909. cmd.Transaction = tx;
  910. if (times > 0)
  911. {
  912. cmd.CommandTimeout = times;
  913. }
  914. try
  915. {
  916. int count = 0;
  917. if (SQLStringList.Count > 0)
  918. {
  919. for (int n = 0; n < SQLStringList.Count; n++)
  920. {
  921. currentCount++;
  922. string strsql = SQLStringList[n];
  923. if (strsql.Trim().Length > 1)
  924. {
  925. cmd.CommandText = strsql;
  926. count += cmd.ExecuteNonQuery();
  927. }
  928. if (backgroundWorker != null)
  929. {
  930. try
  931. {
  932. int currentProgres = Convert.ToInt32(1000 / sumCount * currentCount);
  933. backgroundWorker.ReportProgress(currentProgres);
  934. }
  935. catch { }
  936. }
  937. }
  938. tx.Commit();
  939. msg = "成功!";
  940. return SQLStringList.Count;
  941. }
  942. else
  943. {
  944. msg = "失败,错误原因:脚本内容为空!";
  945. return 0;
  946. }
  947. }
  948. catch (System.Data.SqlClient.SqlException ex)
  949. {
  950. msg = "失败,错误原因:" + ex.Message;
  951. tx.Rollback();
  952. return 0;
  953. }
  954. }
  955. }
  956. /// <summary>
  957. /// 执行SQL脚本文件 实现数据库事务。
  958. /// </summary>
  959. /// <param name="sqlScript">SQL脚本内容</param>
  960. /// <param name="msg">返回执行信息</param>
  961. /// <returns></returns>
  962. public static bool ExecuteSqlScriptTextTran(string sqlScript, string iGetConn, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  963. {
  964. bool bl = false;
  965. List<string> SQLStringList = new List<string>();
  966. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  967. for (int i = 0; i < sqlArray.Length; i++)
  968. {
  969. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  970. if (sql.Trim() != "")
  971. {
  972. SQLStringList.Add(sql);
  973. }
  974. }
  975. int ret = ExecuteSqlTran(SQLStringList,iGetConn, ref msg, backgroundWorker, times);
  976. if (ret > 0) {
  977. bl = true;
  978. }
  979. return bl;
  980. }
  981. /// <summary>
  982. /// 执行SQL脚本文件 实现数据库事务。
  983. /// </summary>
  984. /// <param name="sqlScriptFilePath">SQL脚本文件路径</param>
  985. /// <param name="msg">返回执行信息</param>
  986. /// <returns></returns>
  987. public static bool ExecuteSqlScriptFileTran(string sqlScriptFilePath, string iGetConn, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null, int times = -1)
  988. {
  989. if (System.IO.File.Exists(sqlScriptFilePath))
  990. {
  991. string upgradeDatabaseSql = System.IO.File.ReadAllText(sqlScriptFilePath, System.Text.Encoding.UTF8);
  992. return ExecuteSqlScriptTextTran(upgradeDatabaseSql,iGetConn, ref msg, backgroundWorker, times);
  993. }
  994. else
  995. {
  996. msg = "要执行的SQL脚本文件不存在!";
  997. return false;
  998. }
  999. }
  1000. /// <summary>
  1001. /// 执行SQL脚本文件
  1002. /// </summary>
  1003. /// <param name="sqlScript">SQL脚本内容</param>
  1004. /// <param name="msg">返回执行信息</param>
  1005. /// <returns></returns>
  1006. public static bool ExecuteSqlScriptFile(string sqlScript, string iGetConn, ref string msg, System.ComponentModel.BackgroundWorker backgroundWorker = null,int times=-1)
  1007. {
  1008. bool bl = false;
  1009. string[] sqlArray = System.Text.RegularExpressions.Regex.Split(sqlScript, "go\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  1010. //总计数器
  1011. float sumCount = sqlArray.Length;
  1012. //当前计数器
  1013. int currentCount = 0;
  1014. for (int i = 0; i < sqlArray.Length; i++)
  1015. {
  1016. currentCount++;
  1017. string sql = System.Text.RegularExpressions.Regex.Split(sqlArray[i], "\r\ngo", System.Text.RegularExpressions.RegexOptions.IgnoreCase)[0];
  1018. if (sql.Trim() != "")
  1019. {
  1020. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  1021. try
  1022. {
  1023. List<System.Data.SqlClient.SqlParameter> parameterlist = new List<System.Data.SqlClient.SqlParameter>();
  1024. System.Data.SqlClient.SqlParameter[] parameters = parameterlist.ToArray();
  1025. if (times > 0)
  1026. {
  1027. LYFZ.Helper.SQLHelper.ExecuteSql(sql,times,iGetConn, parameters);
  1028. }
  1029. else
  1030. {
  1031. LYFZ.Helper.SQLHelper.ExecuteSql(sql,iGetConn, parameters);
  1032. }
  1033. msg = "成功!";
  1034. bl = true;
  1035. }
  1036. catch (System.Data.SqlClient.SqlException ex)
  1037. {
  1038. msg = "失败,错误原因:" + ex.Message;
  1039. bl = false;
  1040. break;
  1041. }
  1042. }
  1043. if (backgroundWorker != null)
  1044. {
  1045. try
  1046. {
  1047. int currentProgres =Convert.ToInt32(1000 / sumCount * currentCount);
  1048. backgroundWorker.ReportProgress(currentProgres);
  1049. }
  1050. catch { }
  1051. }
  1052. }
  1053. return bl;
  1054. }
  1055. /// <summary>
  1056. /// 执行SQL语句,返回影响的记录数
  1057. /// </summary>
  1058. /// <param name="SQLString">SQL语句</param>
  1059. /// <param name="connString">连接字符串</param>
  1060. /// <returns>影响的记录数</returns>
  1061. public static int ExecuteSql(string SQLString,string connString, params SqlParameter[] cmdParms)
  1062. {
  1063. using (SqlConnection connection = new SqlConnection(connString))
  1064. {
  1065. using (SqlCommand cmd = new SqlCommand())
  1066. {
  1067. try
  1068. {
  1069. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1070. int rows = cmd.ExecuteNonQuery();
  1071. cmd.Parameters.Clear();
  1072. return rows;
  1073. }
  1074. catch (System.Data.SqlClient.SqlException e)
  1075. {
  1076. throw e;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// 执行SQL语句,返回影响的记录数
  1083. /// </summary>
  1084. /// <param name="SQLString">SQL语句</param>
  1085. /// <returns>影响的记录数</returns>
  1086. public static int ExecuteSql(string SQLString, int times, string iGetConn, params SqlParameter[] cmdParms)
  1087. {
  1088. using (SqlConnection connection = new SqlConnection(iGetConn))
  1089. {
  1090. using (SqlCommand cmd = new SqlCommand())
  1091. {
  1092. try
  1093. {
  1094. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1095. cmd.CommandTimeout = times;
  1096. int rows = cmd.ExecuteNonQuery();
  1097. cmd.Parameters.Clear();
  1098. return rows;
  1099. }
  1100. catch (System.Data.SqlClient.SqlException e)
  1101. {
  1102. throw e;
  1103. }
  1104. }
  1105. }
  1106. }
  1107. /// <summary>
  1108. /// 执行多条SQL语句,实现数据库事务。
  1109. /// </summary>
  1110. /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
  1111. public static void ExecuteSqlTran(Hashtable SQLStringList, string iGetConn)
  1112. {
  1113. //循环
  1114. System.Collections.Generic.List<CommandInfo> cmdList = new List<CommandInfo>();
  1115. foreach (DictionaryEntry myDE in SQLStringList)
  1116. {
  1117. string cmdText = myDE.Key.ToString();
  1118. SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
  1119. cmdList.Add(new CommandInfo(cmdText, cmdParms));
  1120. }
  1121. ExecuteSqlTran(cmdList,iGetConn);
  1122. }
  1123. /// <summary>
  1124. /// 执行多条SQL语句,实现数据库事务。
  1125. /// </summary>
  1126. /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
  1127. public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList, string iGetConn)
  1128. {
  1129. return ExecuteSqlTran(cmdList,-1,iGetConn);
  1130. }
  1131. /// <summary>
  1132. /// 执行多条SQL语句,实现数据库事务。
  1133. /// </summary>
  1134. /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
  1135. public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList, int times, string iGetConn)
  1136. {
  1137. using (SqlConnection conn = new SqlConnection(iGetConn))
  1138. {
  1139. conn.Open();
  1140. using (SqlTransaction trans = conn.BeginTransaction())
  1141. {
  1142. SqlCommand cmd = new SqlCommand();
  1143. if (times > 0)
  1144. {
  1145. cmd.CommandTimeout = times;
  1146. }
  1147. try
  1148. {
  1149. int count = 0;
  1150. //循环
  1151. foreach (CommandInfo myDE in cmdList)
  1152. {
  1153. string cmdText = myDE.CommandText;
  1154. SqlParameter[] cmdParms = myDE.Parameters;
  1155. PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
  1156. if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
  1157. {
  1158. if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
  1159. {
  1160. trans.Rollback();
  1161. return 0;
  1162. }
  1163. object obj = cmd.ExecuteScalar();
  1164. bool isHave = false;
  1165. if (obj == null && obj == DBNull.Value)
  1166. {
  1167. isHave = false;
  1168. }
  1169. isHave = Convert.ToInt32(obj) > 0;
  1170. if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
  1171. {
  1172. trans.Rollback();
  1173. return 0;
  1174. }
  1175. if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
  1176. {
  1177. trans.Rollback();
  1178. return 0;
  1179. }
  1180. continue;
  1181. }
  1182. int val = cmd.ExecuteNonQuery();
  1183. count += val;
  1184. if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
  1185. {
  1186. trans.Rollback();
  1187. return 0;
  1188. }
  1189. cmd.Parameters.Clear();
  1190. }
  1191. trans.Commit();
  1192. return count;
  1193. }
  1194. catch
  1195. {
  1196. trans.Rollback();
  1197. throw;
  1198. }
  1199. }
  1200. }
  1201. }
  1202. /// <summary>
  1203. /// 执行一条计算查询结果语句,返回查询结果(object)。
  1204. /// </summary>
  1205. /// <param name="SQLString">计算查询结果语句</param>
  1206. /// <returns>查询结果(object)</returns>
  1207. public static object GetSingle(string SQLString, string iGetConn, params SqlParameter[] cmdParms)
  1208. {
  1209. using (SqlConnection connection = new SqlConnection(iGetConn))
  1210. {
  1211. using (SqlCommand cmd = new SqlCommand())
  1212. {
  1213. try
  1214. {
  1215. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1216. object obj = cmd.ExecuteScalar();
  1217. cmd.Parameters.Clear();
  1218. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  1219. {
  1220. return null;
  1221. }
  1222. else
  1223. {
  1224. return obj;
  1225. }
  1226. }
  1227. catch (System.Data.SqlClient.SqlException e)
  1228. {
  1229. throw e;
  1230. }
  1231. }
  1232. }
  1233. }
  1234. /// <summary>
  1235. /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  1236. /// </summary>
  1237. /// <param name="strSQL">查询语句</param>
  1238. /// <returns>SqlDataReader</returns>
  1239. public static SqlDataReader ExecuteReader(string SQLString, string iGetConn, params SqlParameter[] cmdParms)
  1240. {
  1241. SqlConnection connection = new SqlConnection(iGetConn);
  1242. SqlCommand cmd = new SqlCommand();
  1243. try
  1244. {
  1245. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1246. SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  1247. cmd.Parameters.Clear();
  1248. return myReader;
  1249. }
  1250. catch (System.Data.SqlClient.SqlException e)
  1251. {
  1252. throw e;
  1253. }
  1254. // finally
  1255. // {
  1256. // cmd.Dispose();
  1257. // connection.Close();
  1258. // }
  1259. }
  1260. /// <summary>
  1261. /// 执行查询语句,返回DataSet
  1262. /// </summary>
  1263. /// <param name="SQLString">查询语句</param>
  1264. /// <returns>DataSet</returns>
  1265. public static DataSet MasterQuery(string SQLString, params SqlParameter[] cmdParms)
  1266. {
  1267. return Query(SQLString, GetMasterConnString(), cmdParms);
  1268. }
  1269. /// <summary>
  1270. /// 执行查询语句,返回DataSet
  1271. /// </summary>
  1272. /// <param name="SQLString">查询语句</param>
  1273. /// <returns>DataSet</returns>
  1274. public static DataSet Query(string SQLString, int times, string iGetConn, params SqlParameter[] cmdParms)
  1275. {
  1276. using (SqlConnection connection = new SqlConnection(iGetConn))
  1277. {
  1278. SqlCommand cmd = new SqlCommand();
  1279. cmd.CommandTimeout = times;
  1280. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1281. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1282. {
  1283. DataSet ds = new DataSet();
  1284. try
  1285. {
  1286. da.Fill(ds, "ds");
  1287. cmd.Parameters.Clear();
  1288. }
  1289. catch (System.Data.SqlClient.SqlException ex)
  1290. {
  1291. throw new Exception(ex.Message);
  1292. }
  1293. return ds;
  1294. }
  1295. }
  1296. }
  1297. /// <summary>
  1298. /// 执行查询语句,返回DataSet
  1299. /// </summary>
  1300. /// <param name="SQLString">查询语句</param>
  1301. /// <param name="connString">数据连接字符串</param>
  1302. /// <returns>DataSet</returns>
  1303. public static DataSet Query(string SQLString, string connString, params SqlParameter[] cmdParms)
  1304. {
  1305. using (SqlConnection connection = new SqlConnection(connString))
  1306. {
  1307. SqlCommand cmd = new SqlCommand();
  1308. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  1309. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  1310. {
  1311. DataSet ds = new DataSet();
  1312. try
  1313. {
  1314. da.Fill(ds, "ds");
  1315. cmd.Parameters.Clear();
  1316. }
  1317. catch (System.Data.SqlClient.SqlException ex)
  1318. {
  1319. throw new Exception(ex.Message);
  1320. }
  1321. return ds;
  1322. }
  1323. }
  1324. }
  1325. public static void PublicPrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1326. {
  1327. PrepareCommand(cmd,conn,trans,cmdText,cmdParms);
  1328. }
  1329. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  1330. {
  1331. if (conn.State != ConnectionState.Open)
  1332. conn.Open();
  1333. cmd.Connection = conn;
  1334. cmd.CommandText = cmdText;
  1335. if (trans != null)
  1336. cmd.Transaction = trans;
  1337. cmd.CommandType = CommandType.Text;//cmdType;
  1338. if (cmdParms != null)
  1339. {
  1340. foreach (SqlParameter parameter in cmdParms)
  1341. {
  1342. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1343. (parameter.Value == null))
  1344. {
  1345. parameter.Value = DBNull.Value;
  1346. }
  1347. cmd.Parameters.Add(parameter);
  1348. }
  1349. }
  1350. }
  1351. #endregion
  1352. #region 存储过程操作
  1353. /// <summary>
  1354. /// 执行存储过程
  1355. /// </summary>
  1356. /// <param name="storedProcName">存储过程名</param>
  1357. /// <param name="parameters">存储过程参数</param>
  1358. /// <param name="tableName">DataSet结果中的表名</param>
  1359. /// <returns>DataSet</returns>
  1360. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, string iGetConn)
  1361. {
  1362. using (SqlConnection connection = new SqlConnection(iGetConn))
  1363. {
  1364. DataSet dataSet = new DataSet();
  1365. connection.Open();
  1366. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1367. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1368. sqlDA.Fill(dataSet, tableName);
  1369. connection.Close();
  1370. return dataSet;
  1371. }
  1372. }
  1373. public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times, string iGetConn)
  1374. {
  1375. using (SqlConnection connection = new SqlConnection(iGetConn))
  1376. {
  1377. DataSet dataSet = new DataSet();
  1378. connection.Open();
  1379. SqlDataAdapter sqlDA = new SqlDataAdapter();
  1380. sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
  1381. sqlDA.SelectCommand.CommandTimeout = Times;
  1382. sqlDA.Fill(dataSet, tableName);
  1383. connection.Close();
  1384. return dataSet;
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// 执行存储过程,返回影响的行数
  1389. /// </summary>
  1390. /// <param name="storedProcName">存储过程名</param>
  1391. /// <param name="parameters">存储过程参数</param>
  1392. /// <param name="rowsAffected">影响的行数</param>
  1393. /// <returns></returns>
  1394. public static int RunProcedure(string storedProcName, IDataParameter[] parameters, string iGetConn, out int rowsAffected)
  1395. {
  1396. using (SqlConnection connection = new SqlConnection(iGetConn))
  1397. {
  1398. int result;
  1399. connection.Open();
  1400. SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
  1401. rowsAffected = command.ExecuteNonQuery();
  1402. result = (int)command.Parameters["ReturnValue"].Value;
  1403. //Connection.Close();
  1404. return result;
  1405. }
  1406. }
  1407. /// <summary>
  1408. /// 创建 SqlCommand 对象实例(用来返回一个整数值)
  1409. /// </summary>
  1410. /// <param name="storedProcName">存储过程名</param>
  1411. /// <param name="parameters">存储过程参数</param>
  1412. /// <returns>SqlCommand 对象实例</returns>
  1413. private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1414. {
  1415. SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
  1416. command.Parameters.Add(new SqlParameter("ReturnValue",
  1417. SqlDbType.Int, 4, ParameterDirection.ReturnValue,
  1418. false, 0, 0, string.Empty, DataRowVersion.Default, null));
  1419. return command;
  1420. }
  1421. /// <summary>
  1422. /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
  1423. /// </summary>
  1424. /// <param name="connection">数据库连接</param>
  1425. /// <param name="storedProcName">存储过程名</param>
  1426. /// <param name="parameters">存储过程参数</param>
  1427. /// <returns>SqlCommand</returns>
  1428. private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
  1429. {
  1430. SqlCommand command = new SqlCommand(storedProcName, connection);
  1431. command.CommandType = CommandType.StoredProcedure;
  1432. foreach (SqlParameter parameter in parameters)
  1433. {
  1434. if (parameter != null)
  1435. {
  1436. // 检查未分配值的输出参数,将其分配以DBNull.Value.
  1437. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  1438. (parameter.Value == null))
  1439. {
  1440. parameter.Value = DBNull.Value;
  1441. }
  1442. command.Parameters.Add(parameter);
  1443. }
  1444. }
  1445. return command;
  1446. }
  1447. #endregion
  1448. }
  1449. }