OdbcCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. string commandText;
  53. int timeout;
  54. CommandType commandType;
  55. UpdateRowSource updateRowSource = UpdateRowSource.Both;
  56. OdbcConnection connection;
  57. OdbcTransaction transaction;
  58. OdbcParameterCollection _parameters;
  59. bool designTimeVisible;
  60. bool prepared=false;
  61. IntPtr hstmt = IntPtr.Zero;
  62. bool disposed = false;
  63. #endregion // Fields
  64. #region Constructors
  65. public OdbcCommand ()
  66. {
  67. this.CommandText = String.Empty;
  68. this.CommandTimeout = 30; // default timeout
  69. this.CommandType = CommandType.Text;
  70. Connection = null;
  71. _parameters = new OdbcParameterCollection ();
  72. Transaction = null;
  73. designTimeVisible = false;
  74. #if ONLY_1_1
  75. updateRowSource = UpdateRowSource.Both;
  76. #endif // ONLY_1_1
  77. }
  78. public OdbcCommand (string cmdText) : this ()
  79. {
  80. CommandText = cmdText;
  81. }
  82. public OdbcCommand (string cmdText, OdbcConnection connection)
  83. : this (cmdText)
  84. {
  85. Connection = connection;
  86. }
  87. public OdbcCommand (string cmdText,
  88. OdbcConnection connection,
  89. OdbcTransaction transaction) : this (cmdText, connection)
  90. {
  91. this.Transaction = transaction;
  92. }
  93. #endregion // Constructors
  94. #region Properties
  95. internal IntPtr hStmt
  96. {
  97. get { return hstmt; }
  98. }
  99. [OdbcCategory ("Data")]
  100. [DefaultValue ("")]
  101. [OdbcDescriptionAttribute ("Command text to execute")]
  102. [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  103. [RefreshPropertiesAttribute (RefreshProperties.All)]
  104. public
  105. #if NET_2_0
  106. override
  107. #endif
  108. string CommandText
  109. {
  110. get { return commandText; }
  111. set {
  112. prepared=false;
  113. commandText = value;
  114. }
  115. }
  116. [OdbcDescriptionAttribute ("Time to wait for command to execute")]
  117. #if NET_1_0 || ONLY_1_1
  118. [DefaultValue (30)]
  119. #endif
  120. public
  121. #if NET_2_0
  122. override
  123. #endif
  124. int CommandTimeout {
  125. get { return timeout; }
  126. set { timeout = value; }
  127. }
  128. [OdbcCategory ("Data")]
  129. [DefaultValue ("Text")]
  130. [OdbcDescriptionAttribute ("How to interpret the CommandText")]
  131. [RefreshPropertiesAttribute (RefreshProperties.All)]
  132. public
  133. #if NET_2_0
  134. override
  135. #endif
  136. CommandType CommandType {
  137. get { return commandType; }
  138. set { commandType = value; }
  139. }
  140. #if ONLY_1_1
  141. [OdbcCategory ("Behavior")]
  142. [OdbcDescriptionAttribute ("Connection used by the command")]
  143. [DefaultValue (null)]
  144. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  145. public OdbcConnection Connection {
  146. get {
  147. return connection;
  148. }
  149. set {
  150. connection = value;
  151. }
  152. }
  153. #endif // ONLY_1_1
  154. #if NET_2_0
  155. [DefaultValue (null)]
  156. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  157. public new OdbcConnection Connection
  158. {
  159. get { return DbConnection as OdbcConnection; }
  160. set { DbConnection = value; }
  161. }
  162. #endif // NET_2_0
  163. [BrowsableAttribute (false)]
  164. [DesignOnlyAttribute (true)]
  165. [DefaultValue (true)]
  166. #if NET_2_0
  167. [EditorBrowsable (EditorBrowsableState.Never)]
  168. #endif
  169. public
  170. #if NET_2_0
  171. override
  172. #endif
  173. bool DesignTimeVisible {
  174. get {
  175. return designTimeVisible;
  176. }
  177. set {
  178. designTimeVisible = value;
  179. }
  180. }
  181. [OdbcCategory ("Data")]
  182. [OdbcDescriptionAttribute ("The parameters collection")]
  183. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
  184. public
  185. #if NET_2_0
  186. new
  187. #endif // NET_2_0
  188. OdbcParameterCollection Parameters {
  189. get {
  190. #if ONLY_1_1
  191. return _parameters;
  192. #else
  193. return base.Parameters as OdbcParameterCollection;
  194. #endif // ONLY_1_1
  195. }
  196. }
  197. [BrowsableAttribute (false)]
  198. [OdbcDescriptionAttribute ("The transaction used by the command")]
  199. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  200. public
  201. #if NET_2_0
  202. new
  203. #endif // NET_2_0
  204. OdbcTransaction Transaction {
  205. get {
  206. return transaction;
  207. }
  208. set {
  209. transaction = value;
  210. }
  211. }
  212. [OdbcCategory ("Behavior")]
  213. [DefaultValue (UpdateRowSource.Both)]
  214. [OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
  215. public
  216. #if NET_2_0
  217. override
  218. #endif
  219. UpdateRowSource UpdatedRowSource {
  220. get {
  221. return updateRowSource;
  222. }
  223. set {
  224. updateRowSource = value;
  225. }
  226. }
  227. #if NET_2_0
  228. protected override DbConnection DbConnection
  229. {
  230. get { return connection; }
  231. set {
  232. connection = (OdbcConnection) value;
  233. }
  234. }
  235. #endif // NET_2_0
  236. #if ONLY_1_1
  237. IDbConnection IDbCommand.Connection {
  238. get {
  239. return Connection;
  240. }
  241. set {
  242. Connection = (OdbcConnection) value;
  243. }
  244. }
  245. IDataParameterCollection IDbCommand.Parameters {
  246. get {
  247. return Parameters;
  248. }
  249. }
  250. #else
  251. protected override DbParameterCollection DbParameterCollection
  252. {
  253. get { return _parameters as DbParameterCollection;}
  254. }
  255. #endif // NET_2_0
  256. #if ONLY_1_1
  257. IDbTransaction IDbCommand.Transaction {
  258. get {
  259. return (IDbTransaction) Transaction;
  260. }
  261. set {
  262. if (value is OdbcTransaction)
  263. {
  264. Transaction = (OdbcTransaction)value;
  265. }
  266. else
  267. {
  268. throw new ArgumentException ();
  269. }
  270. }
  271. }
  272. #else
  273. protected override DbTransaction DbTransaction
  274. {
  275. get { return transaction; }
  276. set {
  277. transaction = (OdbcTransaction)value;
  278. }
  279. }
  280. #endif // ONLY_1_1
  281. #endregion // Properties
  282. #region Methods
  283. public
  284. #if NET_2_0
  285. override
  286. #endif // NET_2_0
  287. void Cancel ()
  288. {
  289. if (hstmt!=IntPtr.Zero)
  290. {
  291. OdbcReturn Ret=libodbc.SQLCancel(hstmt);
  292. if ((Ret!=OdbcReturn.Success) && (Ret!=OdbcReturn.SuccessWithInfo))
  293. throw new OdbcException(new OdbcError("SQLCancel",OdbcHandleType.Stmt,hstmt));
  294. }
  295. else
  296. throw new InvalidOperationException();
  297. }
  298. #if ONLY_1_1
  299. IDbDataParameter IDbCommand.CreateParameter ()
  300. {
  301. return CreateParameter ();
  302. }
  303. #else
  304. protected override DbParameter CreateDbParameter ()
  305. {
  306. return CreateParameter ();
  307. }
  308. #endif // ONLY_1_1
  309. public new OdbcParameter CreateParameter ()
  310. {
  311. return new OdbcParameter ();
  312. }
  313. protected override void Dispose (bool disposing)
  314. {
  315. if (disposed)
  316. return;
  317. FreeStatement (); // free handles
  318. Connection = null;
  319. Transaction = null;
  320. disposed = true;
  321. }
  322. private IntPtr ReAllocStatment ()
  323. {
  324. OdbcReturn ret;
  325. if (hstmt != IntPtr.Zero)
  326. FreeStatement ();
  327. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
  328. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  329. throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
  330. disposed = false;
  331. return hstmt;
  332. }
  333. private void FreeStatement ()
  334. {
  335. if (hstmt == IntPtr.Zero)
  336. return;
  337. // free previously allocated handle.
  338. OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
  339. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  340. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  341. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
  342. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  343. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
  344. hstmt = IntPtr.Zero;
  345. }
  346. private void ExecSQL(string sql)
  347. {
  348. OdbcReturn ret;
  349. if (! prepared && Parameters.Count <= 0) {
  350. ReAllocStatment ();
  351. ret = libodbc.SQLExecDirect (hstmt, sql, libodbc.SQL_NTS);
  352. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo) &&
  353. (ret != OdbcReturn.NoData))
  354. throw new OdbcException(new OdbcError("SQLExecDirect",OdbcHandleType.Stmt,hstmt));
  355. return;
  356. }
  357. if (!prepared)
  358. Prepare();
  359. BindParameters ();
  360. ret=libodbc.SQLExecute(hstmt);
  361. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  362. throw new OdbcException(new OdbcError("SQLExecute",OdbcHandleType.Stmt,hstmt));
  363. }
  364. internal void FreeIfNotPrepared ()
  365. {
  366. if (! prepared)
  367. FreeStatement ();
  368. }
  369. public
  370. #if NET_2_0
  371. override
  372. #endif // NET_2_0
  373. int ExecuteNonQuery ()
  374. {
  375. return ExecuteNonQuery (true);
  376. }
  377. private int ExecuteNonQuery (bool freeHandle)
  378. {
  379. int records = 0;
  380. if (Connection == null)
  381. throw new InvalidOperationException ("No open connection");
  382. if (Connection.State == ConnectionState.Closed)
  383. throw new InvalidOperationException ("Connection state is closed");
  384. // FIXME: a third check is mentioned in .NET docs
  385. ExecSQL(CommandText);
  386. // .NET documentation says that except for INSERT, UPDATE and
  387. // DELETE where the return value is the number of rows affected
  388. // for the rest of the commands the return value is -1.
  389. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  390. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  391. (CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
  392. int numrows = 0;
  393. OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
  394. records = numrows;
  395. }
  396. else
  397. records = -1;
  398. if (freeHandle && !prepared)
  399. FreeStatement ();
  400. return records;
  401. }
  402. public
  403. #if NET_2_0
  404. override
  405. #endif // NET_2_0
  406. void Prepare()
  407. {
  408. ReAllocStatment ();
  409. OdbcReturn ret;
  410. ret=libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
  411. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  412. throw new OdbcException(new OdbcError("SQLPrepare",OdbcHandleType.Stmt,hstmt));
  413. prepared=true;
  414. }
  415. private void BindParameters ()
  416. {
  417. int i=1;
  418. foreach (OdbcParameter p in Parameters)
  419. {
  420. p.Bind(hstmt, i);
  421. p.CopyValue ();
  422. i++;
  423. }
  424. }
  425. public
  426. #if NET_2_0
  427. new
  428. #endif // NET_2_0
  429. OdbcDataReader ExecuteReader ()
  430. {
  431. return ExecuteReader (CommandBehavior.Default);
  432. }
  433. #if ONLY_1_1
  434. IDataReader IDbCommand.ExecuteReader ()
  435. {
  436. return ExecuteReader ();
  437. }
  438. #else
  439. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  440. {
  441. return ExecuteReader (behavior);
  442. }
  443. #endif // ONLY_1_1
  444. public
  445. #if NET_2_0
  446. new
  447. #endif // NET_2_0
  448. OdbcDataReader ExecuteReader (CommandBehavior behavior)
  449. {
  450. int recordsAffected = ExecuteNonQuery(false);
  451. OdbcDataReader dataReader=new OdbcDataReader(this, behavior, recordsAffected);
  452. return dataReader;
  453. }
  454. #if ONLY_1_1
  455. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  456. {
  457. return ExecuteReader (behavior);
  458. }
  459. #endif // ONLY_1_1
  460. public
  461. #if NET_2_0
  462. override
  463. #endif
  464. object ExecuteScalar ()
  465. {
  466. object val = null;
  467. OdbcDataReader reader=ExecuteReader();
  468. try
  469. {
  470. if (reader.Read ())
  471. val=reader[0];
  472. }
  473. finally
  474. {
  475. reader.Close();
  476. }
  477. return val;
  478. }
  479. [MonoTODO]
  480. object ICloneable.Clone ()
  481. {
  482. throw new NotImplementedException ();
  483. }
  484. public void ResetCommandTimeout ()
  485. {
  486. CommandTimeout = 30;
  487. }
  488. #endregion
  489. }
  490. }