SqlCommand.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. //
  2. // System.Data.SqlClient.SqlCommand.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Diego Caravana ([email protected])
  9. //
  10. // (C) Ximian, Inc 2002 http://www.ximian.com/
  11. // (C) Daniel Morgan, 2002
  12. // Copyright (C) Tim Coleman, 2002
  13. //
  14. using Mono.Data.Tds;
  15. using Mono.Data.Tds.Protocol;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Specialized;
  19. using System.ComponentModel;
  20. using System.Data;
  21. using System.Data.Common;
  22. using System.Runtime.InteropServices;
  23. using System.Text;
  24. using System.Xml;
  25. namespace System.Data.SqlClient {
  26. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  27. {
  28. #region Fields
  29. bool disposed = false;
  30. int commandTimeout;
  31. bool designTimeVisible;
  32. string commandText;
  33. CommandType commandType;
  34. SqlConnection connection;
  35. SqlTransaction transaction;
  36. UpdateRowSource updatedRowSource;
  37. CommandBehavior behavior = CommandBehavior.Default;
  38. SqlParameterCollection parameters;
  39. string preparedStatement = null;
  40. #endregion // Fields
  41. #region Constructors
  42. public SqlCommand()
  43. : this (String.Empty, null, null)
  44. {
  45. }
  46. public SqlCommand (string commandText)
  47. : this (commandText, null, null)
  48. {
  49. commandText = commandText;
  50. }
  51. public SqlCommand (string commandText, SqlConnection connection)
  52. : this (commandText, connection, null)
  53. {
  54. Connection = connection;
  55. }
  56. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  57. {
  58. this.commandText = commandText;
  59. this.connection = connection;
  60. this.transaction = transaction;
  61. this.commandType = CommandType.Text;
  62. this.updatedRowSource = UpdateRowSource.Both;
  63. this.designTimeVisible = false;
  64. this.commandTimeout = 30;
  65. parameters = new SqlParameterCollection (this);
  66. }
  67. #endregion // Constructors
  68. #region Properties
  69. internal CommandBehavior CommandBehavior {
  70. get { return behavior; }
  71. }
  72. [DataCategory ("Data")]
  73. [DataSysDescription ("Command text to execute.")]
  74. [DefaultValue ("")]
  75. [RefreshProperties (RefreshProperties.All)]
  76. public string CommandText {
  77. get { return commandText; }
  78. set {
  79. if (value != commandText && preparedStatement != null)
  80. Unprepare ();
  81. commandText = value;
  82. }
  83. }
  84. [DataSysDescription ("Time to wait for command to execute.")]
  85. [DefaultValue (30)]
  86. public int CommandTimeout {
  87. get { return commandTimeout; }
  88. set {
  89. if (commandTimeout < 0)
  90. throw new ArgumentException ("The property value assigned is less than 0.");
  91. commandTimeout = value;
  92. }
  93. }
  94. [DataCategory ("Data")]
  95. [DataSysDescription ("How to interpret the CommandText.")]
  96. [DefaultValue (CommandType.Text)]
  97. [RefreshProperties (RefreshProperties.All)]
  98. public CommandType CommandType {
  99. get { return commandType; }
  100. set {
  101. if (value == CommandType.TableDirect)
  102. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  103. commandType = value;
  104. }
  105. }
  106. [DataCategory ("Behavior")]
  107. [DefaultValue (null)]
  108. [DataSysDescription ("Connection used by the command.")]
  109. public SqlConnection Connection {
  110. get { return connection; }
  111. set {
  112. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  113. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  114. transaction = null;
  115. connection = value;
  116. }
  117. }
  118. [Browsable (false)]
  119. [DefaultValue (true)]
  120. [DesignOnly (true)]
  121. public bool DesignTimeVisible {
  122. get { return designTimeVisible; }
  123. set { designTimeVisible = value; }
  124. }
  125. [DataCategory ("Data")]
  126. [DataSysDescription ("The parameters collection.")]
  127. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  128. public SqlParameterCollection Parameters {
  129. get { return parameters; }
  130. }
  131. internal ITds Tds {
  132. get { return Connection.Tds; }
  133. }
  134. IDbConnection IDbCommand.Connection {
  135. get { return Connection; }
  136. set {
  137. if (!(value is SqlConnection))
  138. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  139. Connection = (SqlConnection) value;
  140. }
  141. }
  142. IDataParameterCollection IDbCommand.Parameters {
  143. get { return Parameters; }
  144. }
  145. IDbTransaction IDbCommand.Transaction {
  146. get { return Transaction; }
  147. set {
  148. if (!(value is SqlTransaction))
  149. throw new ArgumentException ();
  150. Transaction = (SqlTransaction) value;
  151. }
  152. }
  153. [Browsable (false)]
  154. [DataSysDescription ("The transaction used by the command.")]
  155. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  156. public SqlTransaction Transaction {
  157. get { return transaction; }
  158. set { transaction = value; }
  159. }
  160. [DataCategory ("Behavior")]
  161. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  162. [DefaultValue (UpdateRowSource.Both)]
  163. public UpdateRowSource UpdatedRowSource {
  164. get { return updatedRowSource; }
  165. set { updatedRowSource = value; }
  166. }
  167. #endregion // Fields
  168. #region Methods
  169. public void Cancel ()
  170. {
  171. if (Connection == null || Connection.Tds == null)
  172. return;
  173. Connection.Tds.Cancel ();
  174. }
  175. internal void CloseDataReader (bool moreResults)
  176. {
  177. Connection.DataReader = null;
  178. if ((behavior & CommandBehavior.CloseConnection) != 0)
  179. Connection.Close ();
  180. }
  181. public SqlParameter CreateParameter ()
  182. {
  183. return new SqlParameter ();
  184. }
  185. internal void DeriveParameters ()
  186. {
  187. if (commandType != CommandType.StoredProcedure)
  188. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  189. ValidateCommand ("DeriveParameters");
  190. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  191. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  192. string sql = "sp_procedure_params_rowset";
  193. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  194. SqlDataReader reader = new SqlDataReader (this);
  195. parameters.Clear ();
  196. object[] dbValues = new object[reader.FieldCount];
  197. while (reader.Read ()) {
  198. reader.GetValues (dbValues);
  199. parameters.Add (new SqlParameter (dbValues));
  200. }
  201. reader.Close ();
  202. }
  203. private void Execute (CommandBehavior behavior, bool wantResults)
  204. {
  205. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  206. if (preparedStatement == null) {
  207. bool schemaOnly = ((CommandBehavior & CommandBehavior.SchemaOnly) > 0);
  208. bool keyInfo = ((CommandBehavior & CommandBehavior.SchemaOnly) > 0);
  209. StringBuilder sql1 = new StringBuilder ();
  210. StringBuilder sql2 = new StringBuilder ();
  211. if (schemaOnly || keyInfo)
  212. sql1.Append ("SET FMTONLY OFF;");
  213. if (keyInfo) {
  214. sql1.Append ("SET NO_BROWSETABLE ON;");
  215. sql2.Append ("SET NO_BROWSETABLE OFF;");
  216. }
  217. if (schemaOnly) {
  218. sql1.Append ("SET FMTONLY ON;");
  219. sql2.Append ("SET FMTONLY OFF;");
  220. }
  221. switch (CommandType) {
  222. case CommandType.StoredProcedure:
  223. if (keyInfo || schemaOnly)
  224. Connection.Tds.Execute (sql1.ToString ());
  225. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  226. if (keyInfo || schemaOnly)
  227. Connection.Tds.Execute (sql2.ToString ());
  228. break;
  229. case CommandType.Text:
  230. string sql = String.Format ("{0}{1}{2}", sql1.ToString (), CommandText, sql2.ToString ());
  231. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  232. break;
  233. }
  234. }
  235. else
  236. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  237. }
  238. public int ExecuteNonQuery ()
  239. {
  240. ValidateCommand ("ExecuteNonQuery");
  241. int result = 0;
  242. try {
  243. Execute (CommandBehavior.Default, false);
  244. result = Connection.Tds.RecordsAffected;
  245. }
  246. catch (TdsTimeoutException e) {
  247. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  248. }
  249. GetOutputParameters ();
  250. return result;
  251. }
  252. public SqlDataReader ExecuteReader ()
  253. {
  254. return ExecuteReader (CommandBehavior.Default);
  255. }
  256. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  257. {
  258. ValidateCommand ("ExecuteReader");
  259. try {
  260. Execute (behavior, true);
  261. }
  262. catch (TdsTimeoutException e) {
  263. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  264. }
  265. Connection.DataReader = new SqlDataReader (this);
  266. return Connection.DataReader;
  267. }
  268. public object ExecuteScalar ()
  269. {
  270. ValidateCommand ("ExecuteScalar");
  271. try {
  272. Execute (CommandBehavior.Default, true);
  273. }
  274. catch (TdsTimeoutException e) {
  275. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  276. }
  277. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  278. return null;
  279. object result = Connection.Tds.ColumnValues [0];
  280. CloseDataReader (true);
  281. return result;
  282. }
  283. public XmlReader ExecuteXmlReader ()
  284. {
  285. ValidateCommand ("ExecuteXmlReader");
  286. try {
  287. Execute (CommandBehavior.Default, true);
  288. }
  289. catch (TdsTimeoutException e) {
  290. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  291. }
  292. SqlDataReader dataReader = new SqlDataReader (this);
  293. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  294. XmlReader xmlReader = new XmlTextReader (textReader);
  295. return xmlReader;
  296. }
  297. internal void GetOutputParameters ()
  298. {
  299. IList list = Connection.Tds.OutputParameters;
  300. if (list != null && list.Count > 0) {
  301. int index = 0;
  302. foreach (SqlParameter parameter in parameters) {
  303. if (parameter.Direction != ParameterDirection.Input) {
  304. parameter.Value = list [index];
  305. index += 1;
  306. }
  307. if (index >= list.Count)
  308. break;
  309. }
  310. }
  311. }
  312. object ICloneable.Clone ()
  313. {
  314. return new SqlCommand (commandText, Connection);
  315. }
  316. IDbDataParameter IDbCommand.CreateParameter ()
  317. {
  318. return CreateParameter ();
  319. }
  320. IDataReader IDbCommand.ExecuteReader ()
  321. {
  322. return ExecuteReader ();
  323. }
  324. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  325. {
  326. return ExecuteReader (behavior);
  327. }
  328. public void Prepare ()
  329. {
  330. ValidateCommand ("Prepare");
  331. if (CommandType == CommandType.Text)
  332. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  333. }
  334. public void ResetCommandTimeout ()
  335. {
  336. commandTimeout = 30;
  337. }
  338. private void Unprepare ()
  339. {
  340. Connection.Tds.Unprepare (preparedStatement);
  341. preparedStatement = null;
  342. }
  343. private void ValidateCommand (string method)
  344. {
  345. if (Connection == null)
  346. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  347. if (Connection.Transaction != null && transaction != Connection.Transaction)
  348. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  349. if (Connection.State != ConnectionState.Open)
  350. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  351. if (commandText == String.Empty || commandText == null)
  352. throw new InvalidOperationException ("The command text for this Command has not been set.");
  353. if (Connection.DataReader != null)
  354. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  355. if (Connection.XmlReader != null)
  356. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  357. }
  358. #endregion // Methods
  359. }
  360. }