OdbcCommand.cs 15 KB

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