OdbcCommand.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //
  2. // System.Data.Odbc.OdbcCommand
  3. //
  4. // Authors:
  5. // Brian Ritchie ([email protected])
  6. //
  7. // Copyright (C) Brian Ritchie, 2002
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.ComponentModel;
  33. using System.Data;
  34. using System.Data.Common;
  35. using System.Collections;
  36. using System.Runtime.InteropServices;
  37. namespace System.Data.Odbc
  38. {
  39. /// <summary>
  40. /// Represents an SQL statement or stored procedure to execute against a data source.
  41. /// </summary>
  42. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.OdbcCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  43. [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
  44. #if NET_2_0
  45. [DefaultEvent ("RecordsAffected")]
  46. public sealed class OdbcCommand : DbCommand, ICloneable
  47. #else
  48. public sealed class OdbcCommand : Component, ICloneable, IDbCommand
  49. #endif //NET_2_0
  50. {
  51. #region Fields
  52. const int DEFAULT_COMMAND_TIMEOUT = 30;
  53. string commandText;
  54. int timeout;
  55. CommandType commandType;
  56. UpdateRowSource updateRowSource;
  57. OdbcConnection connection;
  58. OdbcTransaction transaction;
  59. OdbcParameterCollection _parameters;
  60. bool designTimeVisible;
  61. bool prepared;
  62. IntPtr hstmt = IntPtr.Zero;
  63. bool disposed;
  64. #endregion // Fields
  65. #region Constructors
  66. public OdbcCommand ()
  67. {
  68. timeout = DEFAULT_COMMAND_TIMEOUT;
  69. commandType = CommandType.Text;
  70. _parameters = new OdbcParameterCollection ();
  71. designTimeVisible = true;
  72. updateRowSource = UpdateRowSource.Both;
  73. }
  74. public OdbcCommand (string cmdText) : this ()
  75. {
  76. commandText = cmdText;
  77. }
  78. public OdbcCommand (string cmdText, OdbcConnection connection)
  79. : this (cmdText)
  80. {
  81. Connection = connection;
  82. }
  83. public OdbcCommand (string cmdText, OdbcConnection connection,
  84. OdbcTransaction transaction) : this (cmdText, connection)
  85. {
  86. this.Transaction = transaction;
  87. }
  88. #endregion // Constructors
  89. #region Properties
  90. internal IntPtr hStmt {
  91. get { return hstmt; }
  92. }
  93. [OdbcCategory ("Data")]
  94. [DefaultValue ("")]
  95. [OdbcDescriptionAttribute ("Command text to execute")]
  96. [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  97. [RefreshPropertiesAttribute (RefreshProperties.All)]
  98. public
  99. #if NET_2_0
  100. override
  101. #endif
  102. string CommandText {
  103. get {
  104. if (commandText == null)
  105. return string.Empty;
  106. return commandText;
  107. }
  108. set {
  109. prepared = false;
  110. commandText = value;
  111. }
  112. }
  113. [OdbcDescriptionAttribute ("Time to wait for command to execute")]
  114. #if NET_1_0 || ONLY_1_1
  115. [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
  116. #endif
  117. public
  118. #if NET_2_0
  119. override
  120. #endif
  121. int CommandTimeout {
  122. get { return timeout; }
  123. set { timeout = value; }
  124. }
  125. [OdbcCategory ("Data")]
  126. [DefaultValue ("Text")]
  127. [OdbcDescriptionAttribute ("How to interpret the CommandText")]
  128. [RefreshPropertiesAttribute (RefreshProperties.All)]
  129. public
  130. #if NET_2_0
  131. override
  132. #endif
  133. CommandType CommandType {
  134. get { return commandType; }
  135. set { commandType = value; }
  136. }
  137. #if ONLY_1_1
  138. [OdbcCategory ("Behavior")]
  139. [OdbcDescriptionAttribute ("Connection used by the command")]
  140. [DefaultValue (null)]
  141. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  142. public OdbcConnection Connection {
  143. get {
  144. return connection;
  145. }
  146. set {
  147. connection = value;
  148. }
  149. }
  150. #endif // ONLY_1_1
  151. #if NET_2_0
  152. [DefaultValue (null)]
  153. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  154. public new OdbcConnection Connection {
  155. get { return DbConnection as OdbcConnection; }
  156. set { DbConnection = value; }
  157. }
  158. #endif // NET_2_0
  159. [BrowsableAttribute (false)]
  160. [DesignOnlyAttribute (true)]
  161. [DefaultValue (true)]
  162. #if NET_2_0
  163. [EditorBrowsable (EditorBrowsableState.Never)]
  164. #endif
  165. public
  166. #if NET_2_0
  167. override
  168. #endif
  169. bool DesignTimeVisible {
  170. get {
  171. return designTimeVisible;
  172. }
  173. set {
  174. designTimeVisible = value;
  175. }
  176. }
  177. [OdbcCategory ("Data")]
  178. [OdbcDescriptionAttribute ("The parameters collection")]
  179. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
  180. public
  181. #if NET_2_0
  182. new
  183. #endif // NET_2_0
  184. OdbcParameterCollection Parameters {
  185. get {
  186. #if ONLY_1_1
  187. return _parameters;
  188. #else
  189. return base.Parameters as OdbcParameterCollection;
  190. #endif // ONLY_1_1
  191. }
  192. }
  193. [BrowsableAttribute (false)]
  194. [OdbcDescriptionAttribute ("The transaction used by the command")]
  195. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  196. public
  197. #if NET_2_0
  198. new
  199. #endif // NET_2_0
  200. OdbcTransaction Transaction {
  201. get {
  202. return transaction;
  203. }
  204. set {
  205. transaction = value;
  206. }
  207. }
  208. [OdbcCategory ("Behavior")]
  209. [DefaultValue (UpdateRowSource.Both)]
  210. [OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
  211. public
  212. #if NET_2_0
  213. override
  214. #endif
  215. UpdateRowSource UpdatedRowSource {
  216. get {
  217. return updateRowSource;
  218. }
  219. set {
  220. updateRowSource = value;
  221. }
  222. }
  223. #if NET_2_0
  224. protected override DbConnection DbConnection {
  225. get { return connection; }
  226. set { connection = (OdbcConnection) value;}
  227. }
  228. #endif // NET_2_0
  229. #if ONLY_1_1
  230. IDbConnection IDbCommand.Connection {
  231. get {
  232. return Connection;
  233. }
  234. set {
  235. Connection = (OdbcConnection) value;
  236. }
  237. }
  238. IDataParameterCollection IDbCommand.Parameters {
  239. get {
  240. return Parameters;
  241. }
  242. }
  243. #else
  244. protected override DbParameterCollection DbParameterCollection {
  245. get { return _parameters as DbParameterCollection;}
  246. }
  247. #endif // NET_2_0
  248. #if ONLY_1_1
  249. IDbTransaction IDbCommand.Transaction {
  250. get {
  251. return (IDbTransaction) Transaction;
  252. }
  253. set {
  254. if (value is OdbcTransaction) {
  255. Transaction = (OdbcTransaction) value;
  256. } else {
  257. throw new ArgumentException ();
  258. }
  259. }
  260. }
  261. #else
  262. protected override DbTransaction DbTransaction {
  263. get { return transaction; }
  264. set { transaction = (OdbcTransaction) value; }
  265. }
  266. #endif // ONLY_1_1
  267. #endregion // Properties
  268. #region Methods
  269. public
  270. #if NET_2_0
  271. override
  272. #endif // NET_2_0
  273. void Cancel ()
  274. {
  275. if (hstmt != IntPtr.Zero) {
  276. OdbcReturn Ret = libodbc.SQLCancel (hstmt);
  277. if (Ret != OdbcReturn.Success && Ret != OdbcReturn.SuccessWithInfo)
  278. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  279. } else
  280. throw new InvalidOperationException ();
  281. }
  282. #if ONLY_1_1
  283. IDbDataParameter IDbCommand.CreateParameter ()
  284. {
  285. return CreateParameter ();
  286. }
  287. #else
  288. protected override DbParameter CreateDbParameter ()
  289. {
  290. return CreateParameter ();
  291. }
  292. #endif // ONLY_1_1
  293. public new OdbcParameter CreateParameter ()
  294. {
  295. return new OdbcParameter ();
  296. }
  297. protected override void Dispose (bool disposing)
  298. {
  299. if (disposed)
  300. return;
  301. FreeStatement (); // free handles
  302. Connection = null;
  303. Transaction = null;
  304. disposed = true;
  305. }
  306. private IntPtr ReAllocStatment ()
  307. {
  308. OdbcReturn ret;
  309. if (hstmt != IntPtr.Zero)
  310. FreeStatement ();
  311. ret = libodbc.SQLAllocHandle (OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
  312. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  313. throw connection.CreateOdbcException (OdbcHandleType.Dbc, Connection.hDbc);
  314. disposed = false;
  315. return hstmt;
  316. }
  317. private void FreeStatement ()
  318. {
  319. if (hstmt == IntPtr.Zero)
  320. return;
  321. // free previously allocated handle.
  322. OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
  323. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  324. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  325. ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Stmt, hstmt);
  326. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  327. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  328. hstmt = IntPtr.Zero;
  329. }
  330. private void ExecSQL (string sql)
  331. {
  332. OdbcReturn ret;
  333. if (! prepared && Parameters.Count <= 0) {
  334. ReAllocStatment ();
  335. ret = libodbc.SQLExecDirect (hstmt, sql, libodbc.SQL_NTS);
  336. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo) &&
  337. (ret != OdbcReturn.NoData))
  338. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  339. return;
  340. }
  341. if (!prepared)
  342. Prepare();
  343. BindParameters ();
  344. ret = libodbc.SQLExecute (hstmt);
  345. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  346. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  347. }
  348. internal void FreeIfNotPrepared ()
  349. {
  350. if (! prepared)
  351. FreeStatement ();
  352. }
  353. public
  354. #if NET_2_0
  355. override
  356. #endif // NET_2_0
  357. int ExecuteNonQuery ()
  358. {
  359. return ExecuteNonQuery (true);
  360. }
  361. private int ExecuteNonQuery (bool freeHandle)
  362. {
  363. int records = 0;
  364. if (Connection == null)
  365. throw new InvalidOperationException ("No open connection");
  366. if (Connection.State == ConnectionState.Closed)
  367. throw new InvalidOperationException ("Connection state is closed");
  368. // FIXME: a third check is mentioned in .NET docs
  369. ExecSQL(CommandText);
  370. // .NET documentation says that except for INSERT, UPDATE and
  371. // DELETE where the return value is the number of rows affected
  372. // for the rest of the commands the return value is -1.
  373. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  374. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  375. (CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
  376. int numrows = 0;
  377. OdbcReturn ret = libodbc.SQLRowCount (hstmt, ref numrows);
  378. records = numrows;
  379. } else
  380. records = -1;
  381. if (freeHandle && !prepared)
  382. FreeStatement ();
  383. return records;
  384. }
  385. public
  386. #if NET_2_0
  387. override
  388. #endif // NET_2_0
  389. void Prepare()
  390. {
  391. ReAllocStatment ();
  392. OdbcReturn ret;
  393. ret = libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
  394. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  395. throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
  396. prepared = true;
  397. }
  398. private void BindParameters ()
  399. {
  400. int i = 1;
  401. foreach (OdbcParameter p in Parameters) {
  402. p.Bind (this, hstmt, i);
  403. p.CopyValue ();
  404. i++;
  405. }
  406. }
  407. public
  408. #if NET_2_0
  409. new
  410. #endif // NET_2_0
  411. OdbcDataReader ExecuteReader ()
  412. {
  413. return ExecuteReader (CommandBehavior.Default);
  414. }
  415. #if ONLY_1_1
  416. IDataReader IDbCommand.ExecuteReader ()
  417. {
  418. return ExecuteReader ();
  419. }
  420. #else
  421. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  422. {
  423. return ExecuteReader (behavior);
  424. }
  425. #endif // ONLY_1_1
  426. public
  427. #if NET_2_0
  428. new
  429. #endif // NET_2_0
  430. OdbcDataReader ExecuteReader (CommandBehavior behavior)
  431. {
  432. int recordsAffected = ExecuteNonQuery(false);
  433. OdbcDataReader dataReader = new OdbcDataReader (this, behavior, recordsAffected);
  434. return dataReader;
  435. }
  436. #if ONLY_1_1
  437. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  438. {
  439. return ExecuteReader (behavior);
  440. }
  441. #endif // ONLY_1_1
  442. public
  443. #if NET_2_0
  444. override
  445. #endif
  446. object ExecuteScalar ()
  447. {
  448. object val = null;
  449. OdbcDataReader reader = ExecuteReader();
  450. try {
  451. if (reader.Read ())
  452. val = reader [0];
  453. } finally {
  454. reader.Close ();
  455. }
  456. return val;
  457. }
  458. object ICloneable.Clone ()
  459. {
  460. OdbcCommand command = new OdbcCommand ();
  461. command.CommandText = this.CommandText;
  462. command.CommandTimeout = this.CommandTimeout;
  463. command.CommandType = this.CommandType;
  464. command.Connection = this.Connection;
  465. command.DesignTimeVisible = this.DesignTimeVisible;
  466. foreach (OdbcParameter parameter in this.Parameters)
  467. command.Parameters.Add (parameter);
  468. command.Transaction = this.Transaction;
  469. return command;
  470. }
  471. public void ResetCommandTimeout ()
  472. {
  473. CommandTimeout = DEFAULT_COMMAND_TIMEOUT;
  474. }
  475. #endregion
  476. }
  477. }