TestSqlDataReader.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // 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. }
  68. rdr.Close();
  69. con.Close();
  70. }
  71. [STAThread]
  72. static void Main(string[] args)
  73. {
  74. Test();
  75. }
  76. }
  77. }