Guest User

Introduction to database interaction with C#

a guest
Feb 11th, 2012
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4.  
  5. /// <summary>
  6. /// Demonstrates how to work with SqlConnection objects
  7. /// </summary>
  8. class SqlConnectionDemo
  9. {
  10. static void Main()
  11. {
  12. // 1. Instantiate the connection
  13. SqlConnection conn = new SqlConnection(
  14. "Data Source=(local);Initial Catalog=Northwind;
  15. Integrated Security=SSPI");
  16.  
  17. SqlDataReader rdr = null;
  18.  
  19. try
  20. {
  21. // 2. Open the connection
  22. conn.Open();
  23.  
  24. // 3. Pass the connection to a command object
  25. SqlCommand cmd =
  26. new SqlCommand("select * from Customers", conn);
  27.  
  28. //
  29. // 4. Use the connection
  30. //
  31.  
  32. // get query results
  33. rdr = cmd.ExecuteReader();
  34.  
  35. // print the CustomerID of each record
  36. while (rdr.Read())
  37. {
  38. Console.WriteLine(rdr[0]);
  39. }
  40. }
  41. finally
  42. {
  43. // close the reader
  44. if (rdr != null)
  45. {
  46. rdr.Close();
  47. }
  48.  
  49. // 5. Close the connection
  50. if (conn != null)
  51. {
  52. conn.Close();
  53. }
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment