OdbcCommand.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. {
  277. OdbcReturn Ret=libodbc.SQLCancel(hstmt);
  278. if ((Ret!=OdbcReturn.Success) && (Ret!=OdbcReturn.SuccessWithInfo))
  279. throw new OdbcException(new OdbcError("SQLCancel",OdbcHandleType.Stmt,hstmt));
  280. }
  281. else
  282. throw new InvalidOperationException();
  283. }
  284. #if ONLY_1_1
  285. IDbDataParameter IDbCommand.CreateParameter ()
  286. {
  287. return CreateParameter ();
  288. }
  289. #else
  290. protected override DbParameter CreateDbParameter ()
  291. {
  292. return CreateParameter ();
  293. }
  294. #endif // ONLY_1_1
  295. public new OdbcParameter CreateParameter ()
  296. {
  297. return new OdbcParameter ();
  298. }
  299. protected override void Dispose (bool disposing)
  300. {
  301. if (disposed)
  302. return;
  303. FreeStatement (); // free handles
  304. Connection = null;
  305. Transaction = null;
  306. disposed = true;
  307. }
  308. private IntPtr ReAllocStatment ()
  309. {
  310. OdbcReturn ret;
  311. if (hstmt != IntPtr.Zero)
  312. FreeStatement ();
  313. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
  314. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  315. throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
  316. disposed = false;
  317. return hstmt;
  318. }
  319. private void FreeStatement ()
  320. {
  321. if (hstmt == IntPtr.Zero)
  322. return;
  323. // free previously allocated handle.
  324. OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
  325. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  326. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  327. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
  328. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  329. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
  330. hstmt = IntPtr.Zero;
  331. }
  332. private void ExecSQL (string sql)
  333. {
  334. OdbcReturn ret;
  335. if (! prepared && Parameters.Count <= 0) {
  336. ReAllocStatment ();
  337. ret = libodbc.SQLExecDirect (hstmt, sql, libodbc.SQL_NTS);
  338. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo) &&
  339. (ret != OdbcReturn.NoData))
  340. throw new OdbcException(new OdbcError("SQLExecDirect",OdbcHandleType.Stmt,hstmt));
  341. return;
  342. }
  343. if (!prepared)
  344. Prepare();
  345. BindParameters ();
  346. ret=libodbc.SQLExecute(hstmt);
  347. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  348. throw new OdbcException(new OdbcError("SQLExecute",OdbcHandleType.Stmt,hstmt));
  349. }
  350. internal void FreeIfNotPrepared ()
  351. {
  352. if (! prepared)
  353. FreeStatement ();
  354. }
  355. public
  356. #if NET_2_0
  357. override
  358. #endif // NET_2_0
  359. int ExecuteNonQuery ()
  360. {
  361. return ExecuteNonQuery (true);
  362. }
  363. private int ExecuteNonQuery (bool freeHandle)
  364. {
  365. int records = 0;
  366. if (Connection == null)
  367. throw new InvalidOperationException ("No open connection");
  368. if (Connection.State == ConnectionState.Closed)
  369. throw new InvalidOperationException ("Connection state is closed");
  370. // FIXME: a third check is mentioned in .NET docs
  371. ExecSQL(CommandText);
  372. // .NET documentation says that except for INSERT, UPDATE and
  373. // DELETE where the return value is the number of rows affected
  374. // for the rest of the commands the return value is -1.
  375. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  376. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  377. (CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
  378. int numrows = 0;
  379. OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
  380. records = numrows;
  381. } else
  382. records = -1;
  383. if (freeHandle && !prepared)
  384. FreeStatement ();
  385. return records;
  386. }
  387. public
  388. #if NET_2_0
  389. override
  390. #endif // NET_2_0
  391. void Prepare()
  392. {
  393. ReAllocStatment ();
  394. OdbcReturn ret;
  395. ret=libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
  396. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  397. throw new OdbcException(new OdbcError("SQLPrepare",OdbcHandleType.Stmt,hstmt));
  398. prepared=true;
  399. }
  400. private void BindParameters ()
  401. {
  402. int i=1;
  403. foreach (OdbcParameter p in Parameters)
  404. {
  405. p.Bind(hstmt, i);
  406. p.CopyValue ();
  407. i++;
  408. }
  409. }
  410. public
  411. #if NET_2_0
  412. new
  413. #endif // NET_2_0
  414. OdbcDataReader ExecuteReader ()
  415. {
  416. return ExecuteReader (CommandBehavior.Default);
  417. }
  418. #if ONLY_1_1
  419. IDataReader IDbCommand.ExecuteReader ()
  420. {
  421. return ExecuteReader ();
  422. }
  423. #else
  424. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  425. {
  426. return ExecuteReader (behavior);
  427. }
  428. #endif // ONLY_1_1
  429. public
  430. #if NET_2_0
  431. new
  432. #endif // NET_2_0
  433. OdbcDataReader ExecuteReader (CommandBehavior behavior)
  434. {
  435. int recordsAffected = ExecuteNonQuery(false);
  436. OdbcDataReader dataReader=new OdbcDataReader(this, behavior, recordsAffected);
  437. return dataReader;
  438. }
  439. #if ONLY_1_1
  440. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  441. {
  442. return ExecuteReader (behavior);
  443. }
  444. #endif // ONLY_1_1
  445. public
  446. #if NET_2_0
  447. override
  448. #endif
  449. object ExecuteScalar ()
  450. {
  451. object val = null;
  452. OdbcDataReader reader=ExecuteReader();
  453. try {
  454. if (reader.Read ())
  455. val=reader[0];
  456. } finally {
  457. reader.Close();
  458. }
  459. return val;
  460. }
  461. object ICloneable.Clone ()
  462. {
  463. OdbcCommand command = new OdbcCommand ();
  464. command.CommandText = this.CommandText;
  465. command.CommandTimeout = this.CommandTimeout;
  466. command.CommandType = this.CommandType;
  467. command.Connection = this.Connection;
  468. command.DesignTimeVisible = this.DesignTimeVisible;
  469. foreach (OdbcParameter parameter in this.Parameters)
  470. command.Parameters.Add (parameter);
  471. command.Transaction = this.Transaction;
  472. return command;
  473. }
  474. public void ResetCommandTimeout ()
  475. {
  476. CommandTimeout = DEFAULT_COMMAND_TIMEOUT;
  477. }
  478. #endregion
  479. }
  480. }