SqlCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.TdsClient.Internal;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Specialized;
  17. using System.ComponentModel;
  18. using System.Data;
  19. using System.Data.Common;
  20. using System.Runtime.InteropServices;
  21. using System.Text;
  22. using System.Xml;
  23. namespace System.Data.SqlClient {
  24. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  25. {
  26. #region Fields
  27. int commandTimeout;
  28. bool designTimeVisible;
  29. string commandText;
  30. CommandType commandType;
  31. SqlConnection connection;
  32. SqlTransaction transaction;
  33. UpdateRowSource updatedRowSource;
  34. CommandBehavior behavior = CommandBehavior.Default;
  35. NameValueCollection preparedStatements = new NameValueCollection ();
  36. SqlParameterCollection parameters;
  37. #endregion // Fields
  38. #region Constructors
  39. public SqlCommand()
  40. : this (String.Empty, null, null)
  41. {
  42. }
  43. public SqlCommand (string commandText)
  44. : this (commandText, null, null)
  45. {
  46. commandText = commandText;
  47. }
  48. public SqlCommand (string commandText, SqlConnection connection)
  49. : this (commandText, connection, null)
  50. {
  51. Connection = connection;
  52. }
  53. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  54. {
  55. this.commandText = commandText;
  56. this.connection = connection;
  57. this.transaction = transaction;
  58. this.commandType = CommandType.Text;
  59. this.updatedRowSource = UpdateRowSource.Both;
  60. this.designTimeVisible = false;
  61. this.commandTimeout = 30;
  62. parameters = new SqlParameterCollection (this);
  63. }
  64. #endregion // Constructors
  65. #region Properties
  66. internal CommandBehavior CommandBehavior {
  67. get { return behavior; }
  68. }
  69. [DataSysDescription ("Command text to execute.")]
  70. [DefaultValue ("")]
  71. [RefreshProperties (RefreshProperties.All)]
  72. public string CommandText {
  73. get { return CommandText; }
  74. set { commandText = value; }
  75. }
  76. [DataSysDescription ("Time to wait for command to execute.")]
  77. [DefaultValue (30)]
  78. public int CommandTimeout {
  79. get { return commandTimeout; }
  80. set {
  81. if (commandTimeout < 0)
  82. throw new ArgumentException ("The property value assigned is less than 0.");
  83. commandTimeout = value;
  84. }
  85. }
  86. [DataSysDescription ("How to interpret the CommandText.")]
  87. [DefaultValue (CommandType.Text)]
  88. [RefreshProperties (RefreshProperties.All)]
  89. public CommandType CommandType {
  90. get { return commandType; }
  91. set { commandType = value; }
  92. }
  93. [DefaultValue (null)]
  94. [DataSysDescription ("Connection used by the command.")]
  95. public SqlConnection Connection {
  96. get { return connection; }
  97. set {
  98. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  99. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  100. transaction = null;
  101. connection = value;
  102. }
  103. }
  104. [Browsable (false)]
  105. [DefaultValue (true)]
  106. [DesignOnly (true)]
  107. public bool DesignTimeVisible {
  108. get { return designTimeVisible; }
  109. set { designTimeVisible = value; }
  110. }
  111. [DataSysDescription ("The parameters collection.")]
  112. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  113. public SqlParameterCollection Parameters {
  114. get { return parameters; }
  115. }
  116. internal ITds Tds {
  117. get { return connection.Tds; }
  118. }
  119. IDbConnection IDbCommand.Connection {
  120. get { return Connection; }
  121. set {
  122. if (!(value is SqlConnection))
  123. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  124. Connection = (SqlConnection) value;
  125. }
  126. }
  127. IDataParameterCollection IDbCommand.Parameters {
  128. get { return Parameters; }
  129. }
  130. IDbTransaction IDbCommand.Transaction {
  131. get { return Transaction; }
  132. set {
  133. if (!(value is SqlTransaction))
  134. throw new ArgumentException ();
  135. Transaction = (SqlTransaction) value;
  136. }
  137. }
  138. [Browsable (false)]
  139. [DataSysDescription ("The transaction used by the command.")]
  140. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  141. public SqlTransaction Transaction {
  142. get { return transaction; }
  143. set { transaction = value; }
  144. }
  145. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  146. [DefaultValue (UpdateRowSource.Both)]
  147. public UpdateRowSource UpdatedRowSource {
  148. get { return updatedRowSource; }
  149. set { updatedRowSource = value; }
  150. }
  151. #endregion // Fields
  152. #region Methods
  153. private string BuildCommand ()
  154. {
  155. string statementHandle = preparedStatements [commandText];
  156. if (statementHandle != null) {
  157. string proc = String.Format ("sp_execute {0}", statementHandle);
  158. if (parameters.Count > 0)
  159. proc += ",";
  160. return BuildProcedureCall (proc, parameters);
  161. }
  162. if (commandType == CommandType.StoredProcedure)
  163. return BuildProcedureCall (commandText, parameters);
  164. string sql = String.Empty;
  165. if ((behavior & CommandBehavior.KeyInfo) > 0)
  166. sql += "SET FMTONLY OFF; SET NO_BROWSETABLE ON;";
  167. if ((behavior & CommandBehavior.SchemaOnly) > 0)
  168. sql += "SET FMTONLY ON;";
  169. switch (commandType) {
  170. case CommandType.Text :
  171. sql += commandText;
  172. break;
  173. case CommandType.TableDirect :
  174. sql += String.Format ("select * from {0}", commandText);
  175. break;
  176. default:
  177. throw new InvalidOperationException ("The CommandType was invalid.");
  178. }
  179. return BuildExec (sql);
  180. }
  181. private string BuildExec (string sql)
  182. {
  183. StringBuilder parms = new StringBuilder ();
  184. foreach (SqlParameter parameter in parameters) {
  185. if (parms.Length > 0)
  186. parms.Append (", ");
  187. parms.Append (parameter.Prepare (parameter.ParameterName));
  188. if (parameter.Direction == ParameterDirection.Output)
  189. parms.Append (" output");
  190. }
  191. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  192. SqlParameter parm;
  193. parm = new SqlParameter ("@P1", SqlDbType.NVarChar);
  194. parm.Value = sql;
  195. parm.Size = ((string) parm.Value).Length;
  196. localParameters.Add (parm);
  197. if (parameters.Count > 0) {
  198. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  199. parm.Value = parms.ToString ();
  200. parm.Size = ((string) parm.Value).Length;
  201. localParameters.Add (parm);
  202. }
  203. foreach (SqlParameter p in parameters)
  204. localParameters.Add (p);
  205. return BuildProcedureCall ("sp_executesql", localParameters);
  206. }
  207. private string BuildPrepare ()
  208. {
  209. StringBuilder parms = new StringBuilder ();
  210. foreach (SqlParameter parameter in parameters) {
  211. if (parms.Length > 0)
  212. parms.Append (", ");
  213. parms.Append (parameter.Prepare (parameter.ParameterName));
  214. if (parameter.Direction == ParameterDirection.Output)
  215. parms.Append (" output");
  216. }
  217. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  218. SqlParameter parm;
  219. parm = new SqlParameter ("@P1", SqlDbType.Int);
  220. parm.Direction = ParameterDirection.Output;
  221. localParameters.Add (parm);
  222. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  223. parm.Value = parms.ToString ();
  224. parm.Size = ((string) parm.Value).Length;
  225. localParameters.Add (parm);
  226. parm = new SqlParameter ("@P3", SqlDbType.NVarChar);
  227. parm.Value = commandText;
  228. parm.Size = ((string) parm.Value).Length;
  229. localParameters.Add (parm);
  230. return BuildProcedureCall ("sp_prepare", localParameters);
  231. }
  232. private static string BuildProcedureCall (string procedure, SqlParameterCollection parameters)
  233. {
  234. StringBuilder parms = new StringBuilder ();
  235. StringBuilder declarations = new StringBuilder ();
  236. StringBuilder outParms = new StringBuilder ();
  237. StringBuilder set = new StringBuilder ();
  238. int index = 1;
  239. foreach (SqlParameter parameter in parameters) {
  240. string parmName = String.Format ("@P{0}", index);
  241. switch (parameter.Direction) {
  242. case ParameterDirection.Input :
  243. if (parms.Length > 0)
  244. parms.Append (", ");
  245. parms.Append (FormatParameter (parameter));
  246. break;
  247. case ParameterDirection.Output :
  248. if (parms.Length > 0)
  249. parms.Append (", ");
  250. parms.Append (parmName);
  251. parms.Append (" output");
  252. if (outParms.Length > 0) {
  253. outParms.Append (", ");
  254. declarations.Append (", ");
  255. }
  256. else {
  257. outParms.Append ("select ");
  258. declarations.Append ("declare ");
  259. }
  260. declarations.Append (parameter.Prepare (parmName));
  261. set.Append (String.Format ("set {0}=NULL\n", parmName));
  262. outParms.Append (parmName);
  263. break;
  264. default :
  265. throw new NotImplementedException ("Only support input and output parameters.");
  266. }
  267. index += 1;
  268. }
  269. return String.Format ("{0}\n{1}exec {2} {3}\n{4}", declarations.ToString (), set.ToString (), procedure, parms.ToString (), outParms.ToString ());
  270. }
  271. public void Cancel ()
  272. {
  273. if (connection == null || connection.Tds == null)
  274. return;
  275. connection.Tds.Cancel ();
  276. }
  277. internal void CloseDataReader (bool moreResults)
  278. {
  279. GetOutputParameters ();
  280. connection.DataReader = null;
  281. if ((behavior & CommandBehavior.CloseConnection) != 0)
  282. connection.Close ();
  283. }
  284. public SqlParameter CreateParameter ()
  285. {
  286. return new SqlParameter ();
  287. }
  288. public int ExecuteNonQuery ()
  289. {
  290. ValidateCommand ("ExecuteNonQuery");
  291. int result = connection.Tds.ExecuteNonQuery (BuildCommand ());
  292. GetOutputParameters ();
  293. return result;
  294. }
  295. public SqlDataReader ExecuteReader ()
  296. {
  297. return ExecuteReader (CommandBehavior.Default);
  298. }
  299. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  300. {
  301. ValidateCommand ("ExecuteReader");
  302. this.behavior = behavior;
  303. connection.Tds.ExecuteQuery (BuildCommand ());
  304. connection.DataReader = new SqlDataReader (this);
  305. return connection.DataReader;
  306. }
  307. public object ExecuteScalar ()
  308. {
  309. ValidateCommand ("ExecuteScalar");
  310. connection.Tds.ExecuteQuery (BuildCommand ());
  311. bool moreResults = connection.Tds.NextResult ();
  312. if (!moreResults)
  313. return null;
  314. moreResults = connection.Tds.NextRow ();
  315. if (!moreResults)
  316. return null;
  317. object result = connection.Tds.ColumnValues[0];
  318. CloseDataReader (true);
  319. return result;
  320. }
  321. public XmlReader ExecuteXmlReader ()
  322. {
  323. ValidateCommand ("ExecuteXmlReader");
  324. connection.Tds.ExecuteQuery (BuildCommand ());
  325. SqlDataReader dataReader = new SqlDataReader (this);
  326. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  327. XmlReader xmlReader = new XmlTextReader (textReader);
  328. return xmlReader;
  329. }
  330. static string FormatParameter (SqlParameter parameter)
  331. {
  332. if (parameter.Value == null)
  333. return "NULL";
  334. switch (parameter.SqlDbType) {
  335. case SqlDbType.BigInt :
  336. case SqlDbType.Bit :
  337. case SqlDbType.Decimal :
  338. case SqlDbType.Float :
  339. case SqlDbType.Int :
  340. case SqlDbType.Money :
  341. case SqlDbType.Real :
  342. case SqlDbType.SmallInt :
  343. case SqlDbType.SmallMoney :
  344. case SqlDbType.TinyInt :
  345. return parameter.Value.ToString ();
  346. case SqlDbType.NVarChar :
  347. case SqlDbType.NChar :
  348. return String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  349. default:
  350. return String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  351. }
  352. }
  353. private void GetOutputParameters ()
  354. {
  355. connection.Tds.SkipToEnd ();
  356. IList list = connection.Tds.ColumnValues;
  357. if (list != null && list.Count > 0) {
  358. int index = 0;
  359. foreach (SqlParameter parameter in parameters) {
  360. if (parameter.Direction != ParameterDirection.Input) {
  361. parameter.Value = list [index];
  362. index += 1;
  363. }
  364. if (index >= list.Count)
  365. break;
  366. }
  367. }
  368. }
  369. object ICloneable.Clone ()
  370. {
  371. return new SqlCommand (commandText, connection);
  372. }
  373. IDbDataParameter IDbCommand.CreateParameter ()
  374. {
  375. return CreateParameter ();
  376. }
  377. IDataReader IDbCommand.ExecuteReader ()
  378. {
  379. return ExecuteReader ();
  380. }
  381. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  382. {
  383. return ExecuteReader (behavior);
  384. }
  385. void IDisposable.Dispose ()
  386. {
  387. Dispose (true);
  388. }
  389. public void Prepare ()
  390. {
  391. ValidateCommand ("Prepare");
  392. connection.Tds.ExecuteNonQuery (BuildPrepare ());
  393. if (connection.Tds.OutputParameters.Count == 0 || connection.Tds.OutputParameters[0] == null)
  394. throw new Exception ("Could not prepare the statement.");
  395. preparedStatements [commandText] = ((int) connection.Tds.OutputParameters [0]).ToString ();
  396. }
  397. public void ResetCommandTimeout ()
  398. {
  399. commandTimeout = 30;
  400. }
  401. private void ValidateCommand (string method)
  402. {
  403. if (connection == null)
  404. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  405. if (connection.Transaction != null && transaction != connection.Transaction)
  406. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  407. if (connection.State != ConnectionState.Open)
  408. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  409. if (commandText == String.Empty || commandText == null)
  410. throw new InvalidOperationException ("The command text for this Command has not been set.");
  411. if (connection.DataReader != null)
  412. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  413. if (connection.XmlReader != null)
  414. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  415. }
  416. #endregion // Methods
  417. }
  418. }