C# Read Data From Database

This code lets you read data from the database. By default, MS SQL is mainly used in tutorials regarding .NET. This code connects to a MySQL database. If you are using MS SQL, just rename the classes that starts with MySQL to SQL. This code assumes that you already have a connection object in hand.

MySqlConnection con = ...;
try {
  MySqlCommand cmd = con.createCommand();
  cmd.CommandText = "select username from users where username = 'me'";
  con.Open();
 
  MySqlDataReader dr = cmd.executeReader();
  if (dr.Read()) {
    Console.WriteLine("username = " + dr["username"]);
  }
} catch (Exception e) {
} finally {
  if (con != null) {
    con.Close();
    con.Dispose();
  }
}

Donations appreciated. Every little $ helps. Or click Google +1.

Related Posts Plugin for WordPress, Blogger...

tags: ,

  1. 2 Responses to “C# Read Data From Database”

  2. I wonder why you never answer any of my question about your topic?
    My Daily Thoughts
    Blogger”s Recollections
    Array Of Hopes

    By my daily thoughts on Jan 15, 2009

  3. hi tey, i wonder why you don’t see my replies. i do :) . i reply them here in my posts.

    By tech on Jan 15, 2009

Post a Comment