TestSqlDataReader.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // Test/SqlDataRead.cs
  3. //
  4. // Test to do read a simple forward read only record set.
  5. // Using SqlCommand.ExecuteReader() to return a SqlDataReader
  6. // which can be used to Read a row
  7. // and Get a String or Int32.
  8. //
  9. // Author:
  10. // Daniel Morgan <[email protected]>
  11. //
  12. // (C) 2002 Daniel Morgan
  13. //
  14. using System;
  15. using System.Data;
  16. using System.Data.SqlClient;
  17. namespace TestSystemDataSqlClient
  18. {
  19. class TestSqlDataReader
  20. {
  21. static void Test() {
  22. SqlConnection con = null;
  23. SqlCommand cmd = null;
  24. SqlDataReader rdr = null;
  25. String connectionString = null;
  26. String sql = null;
  27. connectionString =
  28. "host=localhost;" +
  29. "dbname=test;" +
  30. "user=postgres";
  31. sql = "select tid, tdesc, aint4, abpchar " +
  32. "from sometable";
  33. con = new SqlConnection(connectionString);
  34. con.Open();
  35. Console.WriteLine("sql: " +
  36. sql);
  37. cmd = new SqlCommand(sql, con);
  38. rdr = cmd.ExecuteReader();
  39. // get the DataTable that holds
  40. // the schema
  41. DataTable dt = rdr.GetSchemaTable();
  42. // number of columns in the table
  43. Console.WriteLine("dt.Columns.Count: " +
  44. dt.Columns.Count);
  45. // display the schema
  46. for(int c = 0; c < dt.Columns.Count; c++) {
  47. Console.WriteLine("* Column Name: " +
  48. dt.Columns[c].ColumnName);
  49. Console.WriteLine(" MaxLength: " +
  50. dt.Columns[c].MaxLength);
  51. Console.WriteLine(" Type: " +
  52. dt.Columns[c].DataType);
  53. }
  54. int nRows = 0;
  55. // Read and display the rows
  56. while(rdr.Read()) {
  57. Console.WriteLine("Row: " +
  58. rdr["tid"].ToString() + ", " +
  59. rdr["tdesc"].ToString() + ", " +
  60. rdr["aint4"].ToString() + ", " +
  61. rdr["abpchar"].ToString()
  62. );
  63. Console.WriteLine("1: " + rdr.GetString(0));
  64. Console.WriteLine("2: " + rdr.GetString(1));
  65. Console.WriteLine("3: " + rdr.GetInt32(2));
  66. Console.WriteLine("4: " + rdr.GetString(3));
  67. nRows++;
  68. }
  69. Console.WriteLine("Rows: " +
  70. nRows);
  71. rdr.Close();
  72. con.Close();
  73. }
  74. [STAThread]
  75. static void Main(string[] args)
  76. {
  77. Test();
  78. }
  79. }
  80. }