SqlStatement.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Data;
  6. using System.Reflection;
  7. using Oracle.ManagedDataAccess.Client;
  8. using System.Threading;
  9. using System.Data.Common;
  10. using Npgsql;
  11. using MySql.Data.MySqlClient;
  12. namespace Db_Core
  13. {
  14. public class SqlStatement
  15. {
  16. private String strSQL;
  17. private List<int> questionMarkPos = new List<int>();
  18. private object[] values;
  19. private string checkConnectionCmd = "select 1 from dual";
  20. public string connectionString;
  21. DbConnection conn;
  22. private SqlStatement() { }
  23. public SqlStatement(SqlConnString sqlConn)
  24. {
  25. this.connectionString = SqlCommon.GetConnectionString(sqlConn);
  26. }
  27. public SqlStatement(String sqlConn)
  28. {
  29. this.connectionString = sqlConn;
  30. }
  31. public SqlStatement(string strSQL, SqlConnString sqlConn)
  32. {
  33. this.strSQL = strSQL;
  34. this.connectionString = SqlCommon.GetConnectionString(sqlConn);
  35. int openSquareBracketCount = 0, closeSquareBracketCount = 0;
  36. int firstOpenSquareBracketPos = -2, firstCloseSquareBrackPos = -1;
  37. for (int i = 0; i < strSQL.Length; i++)
  38. {
  39. if (strSQL[i] == '?')
  40. questionMarkPos.Add(i);
  41. if (strSQL[i] == '[')
  42. openSquareBracketCount++;
  43. if (strSQL[i] == ']')
  44. closeSquareBracketCount++;
  45. }
  46. // check validate SQL template
  47. if (openSquareBracketCount != closeSquareBracketCount || firstOpenSquareBracketPos > firstCloseSquareBrackPos)
  48. throw new Exception("SQL template incorrect");
  49. values = new object[questionMarkPos.Count];
  50. for (int i = 0; i < values.Length; i++)
  51. values[i] = Missing.Value;
  52. }
  53. public SqlStatement(string strSQL, String connectionString)
  54. {
  55. this.strSQL = strSQL;
  56. this.connectionString = connectionString;
  57. int openSquareBracketCount = 0, closeSquareBracketCount = 0;
  58. int firstOpenSquareBracketPos = -2, firstCloseSquareBrackPos = -1;
  59. for (int i = 0; i < strSQL.Length; i++)
  60. {
  61. if (strSQL[i] == '?')
  62. questionMarkPos.Add(i);
  63. if (strSQL[i] == '[')
  64. openSquareBracketCount++;
  65. if (strSQL[i] == ']')
  66. closeSquareBracketCount++;
  67. }
  68. // check validate SQL template
  69. if (openSquareBracketCount != closeSquareBracketCount || firstOpenSquareBracketPos > firstCloseSquareBrackPos)
  70. throw new Exception("SQL template incorrect");
  71. values = new object[questionMarkPos.Count];
  72. for (int i = 0; i < values.Length; i++)
  73. values[i] = Missing.Value;
  74. }
  75. public static SqlStatement FromString(string strSQL, SqlConnString sqlConn)
  76. {
  77. return new SqlStatement(strSQL, sqlConn);
  78. }
  79. public static SqlStatement FromFile(string sqlFilePath, SqlConnString sqlConn)
  80. {
  81. StreamReader sr = new StreamReader(sqlFilePath);
  82. String str = sr.ReadToEnd();
  83. sr.Close();
  84. return FromString(str, sqlConn);
  85. }
  86. public static String GetSqlStringFromFile(string sqlFilePath)
  87. {
  88. StreamReader sr = new StreamReader(sqlFilePath);
  89. String str = sr.ReadToEnd();
  90. sr.Close();
  91. return str;
  92. }
  93. /// <summary>
  94. /// Set parameter into command.
  95. /// Start index from 0
  96. /// </summary>
  97. /// <param name="index"></param>
  98. /// <param name="value"></param>
  99. public void SetParameter(int index, object value)
  100. {
  101. values[index] = value;
  102. }
  103. public void SetParameters(params object[] args)
  104. {
  105. for (int i = 0; i < args.Length; i++)
  106. SetParameter(i, args[i]);
  107. }
  108. public string GetSQL()
  109. {
  110. StringBuilder result = new StringBuilder(strSQL);
  111. for (int i = 0; i < questionMarkPos.Count; i++)
  112. if (!(values[i] is Missing))
  113. {
  114. int pos = questionMarkPos[i];
  115. int leftBracketPos = pos - 1;
  116. while (leftBracketPos >= 0 && result[leftBracketPos] != '[' && result[leftBracketPos] != ']')
  117. leftBracketPos--;
  118. if (leftBracketPos == -1)
  119. continue;
  120. if (result[leftBracketPos] == ']')
  121. continue;
  122. int rightBracketPos = pos + 1;
  123. while (rightBracketPos < result.Length && result[rightBracketPos] != '[' && result[rightBracketPos] != ']')
  124. rightBracketPos++;
  125. if (rightBracketPos == result.Length)
  126. continue;
  127. if (result[rightBracketPos] == '[')
  128. continue;
  129. result[leftBracketPos] = ' ';
  130. result[rightBracketPos] = ' ';
  131. }
  132. bool replace = false;
  133. for (int i = 0; i < result.Length; i++)
  134. {
  135. char ch = result[i];
  136. if (ch == '[')
  137. replace = true;
  138. if (replace)
  139. result[i] = ' ';
  140. if (ch == ']')
  141. replace = false;
  142. }
  143. int whereIndex = result.ToString().IndexOf("where", StringComparison.OrdinalIgnoreCase);
  144. for (int i = questionMarkPos.Count - 1; i >= 0; i--)
  145. if (!(values[i] is Missing))
  146. {
  147. String temp = null;
  148. if (values[i] == null)
  149. {
  150. for (int j = questionMarkPos[i] - 1; j >= 0; j--)
  151. {
  152. if (result[j] == ' ')
  153. continue;
  154. if (result[j] == '=')
  155. {
  156. if (whereIndex < j)
  157. {
  158. result[j] = ' ';
  159. temp = "is null";
  160. }
  161. else
  162. temp = "null";
  163. break;
  164. }
  165. else
  166. temp = "null";
  167. }
  168. }
  169. else if (values[i] is Enum)
  170. temp = ((int)values[i]).ToString();
  171. else if (values[i] is string)
  172. temp = "'" + values[i].ToString().Replace("'", "''") + "'";
  173. else if (values[i] is DateTime)
  174. temp = "TO_DATE('" + ((DateTime)values[i]).ToString("dd/MM/yyyy HH:mm:ss") + "', 'dd/MM/yyyy hh24:mi:ss')";
  175. //temp = "'" + ((DateTime)values[i]).ToString("yyyy/MM/dd HH:mm:ss") + "'";
  176. else
  177. temp = values[i].ToString();
  178. result.Remove(questionMarkPos[i], 1).Insert(questionMarkPos[i], temp);
  179. }
  180. return result.ToString();
  181. }
  182. public OracleConnection GetConnection()
  183. {
  184. conn = null;
  185. OracleCommand command = null;
  186. int retry = 0;
  187. while (conn == null && retry < 3)
  188. {
  189. try
  190. {
  191. conn = new OracleConnection(connectionString);
  192. if (conn == null)
  193. throw new Exception("Too many connections to database");
  194. conn.Open();
  195. //test command
  196. command = new OracleCommand(checkConnectionCmd, (OracleConnection)conn);
  197. command.ExecuteReader().Close();
  198. return (OracleConnection)conn;
  199. }
  200. catch (Exception ex)
  201. {
  202. retry++;
  203. try
  204. {
  205. if (conn != null)
  206. {
  207. if (conn.State != ConnectionState.Closed)
  208. conn.Close();
  209. }
  210. }
  211. catch { }
  212. finally
  213. {
  214. conn = null;
  215. }
  216. }
  217. }
  218. return (OracleConnection)conn;
  219. }
  220. public DbConnection GetConnection(ConnectionType connType)
  221. {
  222. conn = null;
  223. DbCommand command = null;
  224. int retry = 0;
  225. while (conn == null)
  226. {
  227. try
  228. {
  229. if (connType == ConnectionType.POSTGRE)
  230. {
  231. conn = new NpgsqlConnection(connectionString);
  232. if (conn == null)
  233. throw new Exception("Too many connections to database");
  234. conn.Open();
  235. //test command
  236. //command = new NpgsqlCommand(checkConnectionCmd, (NpgsqlConnection)conn);
  237. //command.ExecuteReader().Close();
  238. return conn;
  239. }
  240. else if (connType == ConnectionType.MYSQL)
  241. {
  242. conn = new MySqlConnection(connectionString);
  243. if (conn == null)
  244. throw new Exception("Too many connections to database");
  245. conn.Open();
  246. //test command
  247. //command = new NpgsqlCommand(checkConnectionCmd, (NpgsqlConnection)conn);
  248. //command.ExecuteReader().Close();
  249. return conn;
  250. }
  251. else
  252. {
  253. conn = new OracleConnection(connectionString);
  254. if (conn == null)
  255. throw new Exception("Too many connections to database");
  256. conn.Open();
  257. //test command
  258. // default is oracle
  259. command = new OracleCommand(checkConnectionCmd, (OracleConnection)conn);
  260. command.CommandTimeout = 120;
  261. command.ExecuteReader().Close();
  262. return conn;
  263. }
  264. }
  265. catch (Exception ex)
  266. {
  267. retry++;
  268. try
  269. {
  270. if (conn != null)
  271. {
  272. if (conn.State != ConnectionState.Closed)
  273. conn.Close();
  274. }
  275. }
  276. catch { }
  277. finally
  278. {
  279. conn = null;
  280. }
  281. if (retry >= 3)
  282. {
  283. throw ex;
  284. }
  285. }
  286. }
  287. return conn;
  288. }
  289. public OracleDataReader ExecuteReader()
  290. {
  291. OracleConnection conn = null;
  292. OracleCommand command = null;
  293. string sql = GetSQL();
  294. try
  295. {
  296. conn = GetConnection();
  297. command = new OracleCommand(sql, conn);
  298. return command.ExecuteReader(CommandBehavior.CloseConnection);
  299. }
  300. catch (Exception e)
  301. {
  302. if (conn != null)
  303. if (conn.State != ConnectionState.Closed)
  304. conn.Close();
  305. throw e;
  306. }
  307. }
  308. public DbDataReader ExecuteReader(ConnectionType connType)
  309. {
  310. DbConnection conn = null;
  311. DbCommand command = null;
  312. string sql = GetSQL();
  313. try
  314. {
  315. conn = GetConnection(connType);
  316. if (connType == ConnectionType.POSTGRE)
  317. {
  318. command = new NpgsqlCommand(sql, (NpgsqlConnection)conn);
  319. return command.ExecuteReader(CommandBehavior.CloseConnection);
  320. }
  321. else if (connType == ConnectionType.MYSQL)
  322. {
  323. command = new MySqlCommand(sql, (MySqlConnection)conn);
  324. return command.ExecuteReader(CommandBehavior.CloseConnection);
  325. }
  326. else
  327. {
  328. command = new OracleCommand(sql, (OracleConnection)conn);
  329. return command.ExecuteReader(CommandBehavior.CloseConnection);
  330. }
  331. }
  332. catch (Exception e)
  333. {
  334. if (conn != null)
  335. if (conn.State != ConnectionState.Closed)
  336. conn.Close();
  337. throw e;
  338. }
  339. }
  340. public void CloseConnection()
  341. {
  342. try
  343. {
  344. if (conn != null)
  345. if (conn.State != ConnectionState.Closed)
  346. conn.Close();
  347. }
  348. catch
  349. { }
  350. }
  351. public object ExecuteScalar()
  352. {
  353. OracleConnection conn = null;
  354. string sql = GetSQL();
  355. try
  356. {
  357. conn = GetConnection();
  358. OracleCommand command = new OracleCommand(sql, conn);
  359. object result = command.ExecuteScalar();
  360. conn.Close();
  361. return result;
  362. }
  363. catch (Exception e)
  364. {
  365. if (conn != null)
  366. if (conn.State != ConnectionState.Closed)
  367. conn.Close();
  368. throw e;
  369. }
  370. }
  371. public int ExecuteNonQuery()
  372. {
  373. OracleConnection conn = null;
  374. string sql = GetSQL();
  375. try
  376. {
  377. conn = GetConnection();
  378. OracleCommand command = new OracleCommand(sql, conn);
  379. int result = command.ExecuteNonQuery();
  380. conn.Close();
  381. return result;
  382. }
  383. catch (Exception e)
  384. {
  385. if (conn != null)
  386. if (conn.State != ConnectionState.Closed)
  387. conn.Close();
  388. throw e;
  389. }
  390. }
  391. public int ExecuteNonQuery(ConnectionType connType)
  392. {
  393. DbConnection conn = null;
  394. string sql = GetSQL();
  395. try
  396. {
  397. conn = GetConnection(connType);
  398. if (connType == ConnectionType.POSTGRE)
  399. {
  400. NpgsqlCommand command = new NpgsqlCommand(sql, (NpgsqlConnection)conn);
  401. int result = command.ExecuteNonQuery();
  402. conn.Close();
  403. return result;
  404. }
  405. else if (connType == ConnectionType.MYSQL)
  406. {
  407. MySqlCommand command = new MySqlCommand(sql, (MySqlConnection)conn);
  408. int result = command.ExecuteNonQuery();
  409. conn.Close();
  410. return result;
  411. }
  412. else
  413. {
  414. OracleCommand command = new OracleCommand(sql, (OracleConnection)conn);
  415. int result = command.ExecuteNonQuery();
  416. conn.Close();
  417. return result;
  418. }
  419. }
  420. catch (Exception e)
  421. {
  422. if (conn != null)
  423. if (conn.State != ConnectionState.Closed)
  424. conn.Close();
  425. throw e;
  426. }
  427. }
  428. }
  429. }