TestExecuteScalar.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // Test/ExecuteScalar.cs
  3. //
  4. // Test the ExecuteScalar method in the
  5. // System.Data.SqlClient.SqlCommand class
  6. //
  7. // ExecuteScalar is meant to be lightweight
  8. // compared to ExecuteReader and only
  9. // returns one column and one row as one object.
  10. //
  11. // It is meant for SELECT SQL statements that
  12. // use an aggregate/group by function, such as,
  13. // count(), sum(), avg(), min(), max(), etc...
  14. //
  15. // The object that is returned you do an
  16. // explicit cast. For instance, to retrieve a
  17. // Count of rows in a PostgreSQL table, you
  18. // would use "SELECT COUNT(*) FROM SOMETABLE"
  19. // which returns a number of oid type 20 which is
  20. // a PostgreSQL int8 which maps to
  21. // the .NET type System.Int64. You
  22. // have to explicitly convert this returned object
  23. // to the type you are expecting, such as, an Int64
  24. // is returned for a COUNT().
  25. // would be:
  26. // Int64 myCount = (Int64) cmd.ExecuteScalar(selectStatement);
  27. //
  28. // Author:
  29. // Daniel Morgan <[email protected]>
  30. //
  31. // (C) 2002 Daniel Morgan
  32. //
  33. using System;
  34. using System.Data;
  35. using System.Data.SqlClient;
  36. namespace TestSystemDataSqlClient
  37. {
  38. class TestSqlDataReader
  39. {
  40. static void Test() {
  41. SqlConnection con = null;
  42. SqlCommand cmd = null;
  43. String connectionString = null;
  44. String sql = null;
  45. connectionString =
  46. "host=localhost;" +
  47. "dbname=test;" +
  48. "user=postgres";
  49. try {
  50. con = new SqlConnection(connectionString);
  51. con.Open();
  52. sql = "select count(*) " +
  53. "from sometable";
  54. cmd = new SqlCommand(sql,con);
  55. Console.WriteLine("Executing...");
  56. Int64 rowCount = (Int64) cmd.ExecuteScalar();
  57. Console.WriteLine("Row Count: " + rowCount);
  58. sql = "select max(tdesc) " +
  59. "from sometable";
  60. cmd = new SqlCommand(sql,con);
  61. Console.WriteLine("Executing...");
  62. String maxValue = (string) cmd.ExecuteScalar();
  63. Console.WriteLine("Max Value: " + maxValue);
  64. }
  65. catch(Exception e) {
  66. Console.WriteLine(e.ToString());
  67. }
  68. finally {
  69. if(con != null)
  70. if(con.State == ConnectionState.Open)
  71. con.Close();
  72. }
  73. }
  74. [STAThread]
  75. static void Main(string[] args)
  76. {
  77. Test();
  78. }
  79. }
  80. }