2
0

SqlCommand.cs 11 KB

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