C# and MySql : Retrieve Data using MySqlDataReader

Leave a Comment
C# and MySql : Retrieve Data using MySqlDataReader

       
  
 String str = @"server=localhost;database=yourDBname;userid=root;password=yourDBpassword;";
MySqlConnection con = null;
//MySqlDataReader Object
MySqlDataReader reader = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
//We will need to SELECT all or some columns in the table
//via this command
String cmdText = "SELECT * FROM myTable";
MySqlCommand cmd = new MySqlCommand(cmdText,con);
reader = cmd.ExecuteReader(); //execure the reader
/*The Read() method points to the next record It return false if there are no more records else returns true.*/
while (reader.Read())
{
/*reader.GetString(0) will get the value of the first column of the table myTable because we selected all columns using SELECT * (all); the first loop of the while loop is the first row; the next loop will be the second row and so on...*/
     Console.WriteLine(reader.GetString(0));
}
}
catch (MySqlException err)
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (reader != null)
{
     reader.Close();
}
if (con != null)
{
     con.Close(); //close the connection
}
} //remember to close the connection after accessing the database
       
 

0 comments:

Post a Comment