LearnFast.Ninja

C# reader database using ODBC

In this tutorial you will see how to fill User class with data from MySQL database using Odbc reader. First we creating a null User instance so if the reading failed our function will be returned a null object. Then we will write our query string and the connection string to the MySQL database. We will write using block and open a connection. In the end of the using block the connection will be closed.

Example:

User oUser = null;

string Query = @"SELECT User_ID, First_Name FROM Users";

 

string MyConnectionString = "Driver={MySQL ODBC 5.1 Driver};Server=127.0.0.1;Uid=Your_User_Name;Pwd=Your_Password;Database=Your_Database_Name;Option=3;";

using (OdbcConnection connection = new OdbcConnection(MyConnectionString))

{

    OdbcCommand command = new OdbcCommand(Query, connection);

    connection.Open();

    OdbcDataReader reader = command.ExecuteReader();

    while (reader.Read())

    {

        string User_ID = reader["User_ID"].ToString();

        string First_Name = reader["First_Name"].ToString();

 

        oUser = User_Builder.Create_Playlist_With_ID_And_Title(Usert_ID, First_Name);

    }

    reader.Close();

}

return oUser;


Tags

asp.net

odbc odbcconnection odbccommand odbcdatareader using mysql