OdbcCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. [DefaultValue (30)]
  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. public new OdbcConnection Connection
  153. {
  154. get { return DbConnection as OdbcConnection; }
  155. set { DbConnection = value; }
  156. }
  157. #endif // NET_2_0
  158. [BrowsableAttribute (false)]
  159. [DesignOnlyAttribute (true)]
  160. [DefaultValue (true)]
  161. public
  162. #if NET_2_0
  163. override
  164. #endif
  165. bool DesignTimeVisible {
  166. get {
  167. return designTimeVisible;
  168. }
  169. set {
  170. designTimeVisible = value;
  171. }
  172. }
  173. [OdbcCategory ("Data")]
  174. [OdbcDescriptionAttribute ("The parameters collection")]
  175. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
  176. public
  177. #if NET_2_0
  178. new
  179. #endif // NET_2_0
  180. OdbcParameterCollection Parameters {
  181. get {
  182. #if ONLY_1_1
  183. return _parameters;
  184. #else
  185. return base.Parameters as OdbcParameterCollection;
  186. #endif // ONLY_1_1
  187. }
  188. }
  189. [BrowsableAttribute (false)]
  190. [OdbcDescriptionAttribute ("The transaction used by the command")]
  191. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  192. public
  193. #if NET_2_0
  194. new
  195. #endif // NET_2_0
  196. OdbcTransaction Transaction {
  197. get {
  198. return transaction;
  199. }
  200. set {
  201. transaction = value;
  202. }
  203. }
  204. [OdbcCategory ("Behavior")]
  205. [DefaultValue (UpdateRowSource.Both)]
  206. [OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
  207. public
  208. #if NET_2_0
  209. override
  210. #endif
  211. UpdateRowSource UpdatedRowSource {
  212. [MonoTODO]
  213. get {
  214. return updateRowSource;
  215. }
  216. [MonoTODO]
  217. set {
  218. updateRowSource = value;
  219. }
  220. }
  221. #if NET_2_0
  222. protected override DbConnection DbConnection
  223. {
  224. get { return connection; }
  225. set {
  226. connection = (OdbcConnection) value;
  227. }
  228. }
  229. #endif // NET_2_0
  230. #if ONLY_1_1
  231. IDbConnection IDbCommand.Connection {
  232. get {
  233. return Connection;
  234. }
  235. set {
  236. Connection = (OdbcConnection) value;
  237. }
  238. }
  239. IDataParameterCollection IDbCommand.Parameters {
  240. get {
  241. return Parameters;
  242. }
  243. }
  244. #else
  245. protected override DbParameterCollection DbParameterCollection
  246. {
  247. get { return _parameters as DbParameterCollection;}
  248. }
  249. #endif // NET_2_0
  250. #if ONLY_1_1
  251. IDbTransaction IDbCommand.Transaction {
  252. get {
  253. return (IDbTransaction) Transaction;
  254. }
  255. set {
  256. if (value is OdbcTransaction)
  257. {
  258. Transaction = (OdbcTransaction)value;
  259. }
  260. else
  261. {
  262. throw new ArgumentException ();
  263. }
  264. }
  265. }
  266. #else
  267. protected override DbTransaction DbTransaction
  268. {
  269. get { return transaction; }
  270. set {
  271. transaction = (OdbcTransaction)value;
  272. }
  273. }
  274. #endif // ONLY_1_1
  275. #endregion // Properties
  276. #region Methods
  277. public
  278. #if NET_2_0
  279. override
  280. #endif // NET_2_0
  281. void Cancel ()
  282. {
  283. if (hstmt!=IntPtr.Zero)
  284. {
  285. OdbcReturn Ret=libodbc.SQLCancel(hstmt);
  286. if ((Ret!=OdbcReturn.Success) && (Ret!=OdbcReturn.SuccessWithInfo))
  287. throw new OdbcException(new OdbcError("SQLCancel",OdbcHandleType.Stmt,hstmt));
  288. }
  289. else
  290. throw new InvalidOperationException();
  291. }
  292. #if ONLY_1_1
  293. IDbDataParameter IDbCommand.CreateParameter ()
  294. {
  295. return CreateParameter ();
  296. }
  297. #else
  298. protected override DbParameter CreateDbParameter ()
  299. {
  300. return CreateParameter ();
  301. }
  302. #endif // ONLY_1_1
  303. public new OdbcParameter CreateParameter ()
  304. {
  305. return new OdbcParameter ();
  306. }
  307. protected override void Dispose (bool disposing)
  308. {
  309. if (disposed)
  310. return;
  311. FreeStatement (); // free handles
  312. Connection = null;
  313. Transaction = null;
  314. disposed = true;
  315. }
  316. private IntPtr ReAllocStatment ()
  317. {
  318. OdbcReturn ret;
  319. if (hstmt != IntPtr.Zero)
  320. FreeStatement ();
  321. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
  322. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  323. throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
  324. disposed = false;
  325. return hstmt;
  326. }
  327. private void FreeStatement ()
  328. {
  329. if (hstmt == IntPtr.Zero)
  330. return;
  331. // free previously allocated handle.
  332. OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
  333. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  334. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  335. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
  336. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  337. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
  338. hstmt = IntPtr.Zero;
  339. }
  340. private void ExecSQL(string sql)
  341. {
  342. OdbcReturn ret;
  343. if (! prepared && Parameters.Count <= 0) {
  344. ReAllocStatment ();
  345. ret=libodbc.SQLExecDirect(hstmt, sql, sql.Length);
  346. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  347. throw new OdbcException(new OdbcError("SQLExecDirect",OdbcHandleType.Stmt,hstmt));
  348. return;
  349. }
  350. if (!prepared)
  351. Prepare();
  352. BindParameters ();
  353. ret=libodbc.SQLExecute(hstmt);
  354. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  355. throw new OdbcException(new OdbcError("SQLExecute",OdbcHandleType.Stmt,hstmt));
  356. }
  357. internal void FreeIfNotPrepared ()
  358. {
  359. if (! prepared)
  360. FreeStatement ();
  361. }
  362. public
  363. #if NET_2_0
  364. override
  365. #endif // NET_2_0
  366. int ExecuteNonQuery ()
  367. {
  368. return ExecuteNonQuery (true);
  369. }
  370. private int ExecuteNonQuery (bool freeHandle)
  371. {
  372. int records = 0;
  373. if (Connection == null)
  374. throw new InvalidOperationException ();
  375. if (Connection.State == ConnectionState.Closed)
  376. throw new InvalidOperationException ();
  377. // FIXME: a third check is mentioned in .NET docs
  378. ExecSQL(CommandText);
  379. // .NET documentation says that except for INSERT, UPDATE and
  380. // DELETE where the return value is the number of rows affected
  381. // for the rest of the commands the return value is -1.
  382. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  383. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  384. (CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
  385. int numrows = 0;
  386. OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
  387. records = numrows;
  388. }
  389. else
  390. records = -1;
  391. if (freeHandle && !prepared)
  392. FreeStatement ();
  393. return records;
  394. }
  395. public
  396. #if NET_2_0
  397. override
  398. #endif // NET_2_0
  399. void Prepare()
  400. {
  401. ReAllocStatment ();
  402. OdbcReturn ret;
  403. ret=libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
  404. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  405. throw new OdbcException(new OdbcError("SQLPrepare",OdbcHandleType.Stmt,hstmt));
  406. prepared=true;
  407. }
  408. private void BindParameters ()
  409. {
  410. int i=1;
  411. foreach (OdbcParameter p in Parameters)
  412. {
  413. p.Bind(hstmt, i);
  414. p.CopyValue ();
  415. i++;
  416. }
  417. }
  418. public
  419. #if NET_2_0
  420. new
  421. #endif // NET_2_0
  422. OdbcDataReader ExecuteReader ()
  423. {
  424. return ExecuteReader (CommandBehavior.Default);
  425. }
  426. #if ONLY_1_1
  427. IDataReader IDbCommand.ExecuteReader ()
  428. {
  429. return ExecuteReader ();
  430. }
  431. #else
  432. protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
  433. {
  434. return ExecuteReader (behavior);
  435. }
  436. #endif // ONLY_1_1
  437. public
  438. #if NET_2_0
  439. new
  440. #endif // NET_2_0
  441. OdbcDataReader ExecuteReader (CommandBehavior behavior)
  442. {
  443. int recordsAffected = ExecuteNonQuery(false);
  444. OdbcDataReader dataReader=new OdbcDataReader(this, behavior, recordsAffected);
  445. return dataReader;
  446. }
  447. #if ONLY_1_1
  448. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  449. {
  450. return ExecuteReader (behavior);
  451. }
  452. #endif // ONLY_1_1
  453. public
  454. #if NET_2_0
  455. override
  456. #endif
  457. object ExecuteScalar ()
  458. {
  459. object val = null;
  460. OdbcDataReader reader=ExecuteReader();
  461. try
  462. {
  463. if (reader.Read ())
  464. val=reader[0];
  465. }
  466. finally
  467. {
  468. reader.Close();
  469. }
  470. return val;
  471. }
  472. [MonoTODO]
  473. object ICloneable.Clone ()
  474. {
  475. throw new NotImplementedException ();
  476. }
  477. public void ResetCommandTimeout ()
  478. {
  479. CommandTimeout = 30;
  480. }
  481. #endregion
  482. }
  483. }