TestSqlDataReader.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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=danmorg;" +
  31. "password=viewsonic";
  32. sql = "select tid, tdesc, aint4, abpchar " +
  33. "from sometable";
  34. con = new SqlConnection(connectionString);
  35. con.Open();
  36. Console.WriteLine("sql: " +
  37. sql);
  38. cmd = new SqlCommand(sql, con);
  39. rdr = cmd.ExecuteReader();
  40. // get the DataTable that holds
  41. // the schema
  42. DataTable dt = rdr.GetSchemaTable();
  43. // number of columns in the table
  44. Console.WriteLine("dt.Columns.Count: " +
  45. dt.Columns.Count);
  46. // display the schema
  47. for(int c = 0; c < dt.Columns.Count; c++) {
  48. Console.WriteLine("* Column Name: " +
  49. dt.Columns[c].ColumnName);
  50. Console.WriteLine(" MaxLength: " +
  51. dt.Columns[c].MaxLength);
  52. Console.WriteLine(" Type: " +
  53. dt.Columns[c].DataType);
  54. }
  55. int nRows = 0;
  56. // Read and display the rows
  57. while(rdr.Read()) {
  58. Console.WriteLine("Row: " +
  59. rdr["tid"].ToString() + ", " +
  60. rdr["tdesc"].ToString() + ", " +
  61. rdr["aint4"].ToString() + ", " +
  62. rdr["abpchar"].ToString()
  63. );
  64. Console.WriteLine("1: " + rdr.GetString(0));
  65. Console.WriteLine("2: " + rdr.GetString(1));
  66. Console.WriteLine("3: " + rdr.GetInt32(2));
  67. Console.WriteLine("4: " + rdr.GetString(3));
  68. nRows++;
  69. }
  70. Console.WriteLine("Rows: " +
  71. nRows);
  72. rdr.Close();
  73. con.Close();
  74. }
  75. [STAThread]
  76. static void Main(string[] args)
  77. {
  78. Test();
  79. }
  80. }
  81. }