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 with Thumbnails

tags: ,

2 Responses to “C# Read Data From Database”

  1. 1
    my daily thoughts Says:

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

  2. 2
    tech Says:

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

Leave a Reply

Spam protection by WP Captcha-Free