OdbcCommand.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. private IntPtr ReAllocStatment ()
  334. {
  335. OdbcReturn ret;
  336. if (hstmt != IntPtr.Zero)
  337. FreeStatement ();
  338. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
  339. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  340. throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
  341. disposed = false;
  342. return hstmt;
  343. }
  344. private void FreeStatement ()
  345. {
  346. if (hstmt == IntPtr.Zero)
  347. return;
  348. // free previously allocated handle.
  349. OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
  350. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  351. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  352. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
  353. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  354. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
  355. hstmt = IntPtr.Zero;
  356. }
  357. private void ExecSQL(string sql)
  358. {
  359. OdbcReturn ret;
  360. if (! prepared && Parameters.Count <= 0) {
  361. ReAllocStatment ();
  362. ret=libodbc.SQLExecDirect(hstmt, sql, sql.Length);
  363. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  364. throw new OdbcException(new OdbcError("SQLExecDirect",OdbcHandleType.Stmt,hstmt));
  365. return;
  366. }
  367. if (!prepared)
  368. Prepare();
  369. BindParameters ();
  370. ret=libodbc.SQLExecute(hstmt);
  371. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  372. throw new OdbcException(new OdbcError("SQLExecute",OdbcHandleType.Stmt,hstmt));
  373. }
  374. internal void FreeIfNotPrepared ()
  375. {
  376. if (! prepared)
  377. FreeStatement ();
  378. }
  379. public
  380. #if NET_2_0
  381. override
  382. #endif // NET_2_0
  383. int ExecuteNonQuery ()
  384. {
  385. return ExecuteNonQuery (true);
  386. }
  387. private int ExecuteNonQuery (bool freeHandle)
  388. {
  389. int records = 0;
  390. if (Connection == null)
  391. throw new InvalidOperationException ();
  392. if (Connection.State == ConnectionState.Closed)
  393. throw new InvalidOperationException ();
  394. // FIXME: a third check is mentioned in .NET docs
  395. ExecSQL(CommandText);
  396. // .NET documentation says that except for INSERT, UPDATE and
  397. // DELETE where the return value is the number of rows affected
  398. // for the rest of the commands the return value is -1.
  399. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  400. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  401. (CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
  402. int numrows = 0;
  403. OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
  404. records = numrows;
  405. }
  406. else
  407. records = -1;
  408. if (freeHandle && !prepared)
  409. FreeStatement ();
  410. return records;
  411. }
  412. public
  413. #if NET_2_0
  414. override
  415. #endif // NET_2_0
  416. void Prepare()
  417. {
  418. ReAllocStatment ();
  419. OdbcReturn ret;
  420. ret=libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
  421. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  422. throw new OdbcException(new OdbcError("SQLPrepare",OdbcHandleType.Stmt,hstmt));
  423. prepared=true;
  424. }
  425. private void BindParameters ()
  426. {
  427. int i=1;
  428. foreach (OdbcParameter p in Parameters)
  429. {
  430. p.Bind(hstmt, i);
  431. p.CopyValue ();
  432. i++;
  433. }
  434. }
  435. public
  436. #if NET_2_0
  437. new
  438. #endif // NET_2_0
  439. OdbcDataReader ExecuteReader ()
  440. {
  441. return ExecuteReader (CommandBehavior.Default);
  442. }
  443. #if ONLY_1_1
  444. IDataReader IDbCommand.ExecuteReader ()
  445. {
  446. return ExecuteReader ();
  447. }
  448. #else
  449. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  450. {
  451. return ExecuteReader (behavior);
  452. }
  453. #endif // ONLY_1_1
  454. public
  455. #if NET_2_0
  456. new
  457. #endif // NET_2_0
  458. OdbcDataReader ExecuteReader (CommandBehavior behavior)
  459. {
  460. int recordsAffected = ExecuteNonQuery(false);
  461. OdbcDataReader dataReader=new OdbcDataReader(this, behavior, recordsAffected);
  462. return dataReader;
  463. }
  464. #if ONLY_1_1
  465. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  466. {
  467. return ExecuteReader (behavior);
  468. }
  469. #endif // ONLY_1_1
  470. #if ONLY_1_1
  471. public object ExecuteScalar ()
  472. {
  473. object val = null;
  474. OdbcDataReader reader=ExecuteReader();
  475. try
  476. {
  477. if (reader.Read ())
  478. val=reader[0];
  479. }
  480. finally
  481. {
  482. reader.Close();
  483. }
  484. return val;
  485. }
  486. #endif // ONLY_1_1
  487. [MonoTODO]
  488. object ICloneable.Clone ()
  489. {
  490. throw new NotImplementedException ();
  491. }
  492. public
  493. #if NET_2_0
  494. override
  495. #endif // NET_2_0
  496. void ResetCommandTimeout ()
  497. {
  498. CommandTimeout = 30;
  499. }
  500. #endregion
  501. }
  502. }