OdbcCommand.cs 15 KB

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