Search 
DailyCoding > Database

Add parameterized queries in MySql (OleDb)

Explains how to add parameters in odbc queries
Author admin on May 18, 2008 0 Comments
Rate it    (Rated 3 by 5 people)
2,077 Views

To connect to MySQL database you can use the System.Data.Odbc namespace in .net

using (OdbcConnection con = new OdbcConnection(connectionString))
{
  using (OdbcCommand cmd = new OdbcCommand())
  {
    cmd.Connection = con;
    cmd.CommandText = "SELECT * FROM Employees";
    using (OdbcDataReader drd = cmd.ExecuteReader())
    {
      while (drd.Read())
      {
        // Read from data reader
      }
    }
  }
}

Adding parameters the queries in System.Data.Odbc works different than System.Data.SqlClient. While using a SqlCommand we add parameters in form of @parameter name. Parameter names are directly mapped to their values.

using (SqlConnection con = new SqlConnection(connectionString))
{
  using (SqlCommand cmd = new SqlCommand())
  {
    cmd.Connection = con;
    cmd.CommandText 
      = "SELECT * FROM Employees WHERE EmployeeId = @EmployeeId ";
    cmd.Parameters.AddWithValue("@EmployeeId", employeeId);
    using (SqlDataReader drd = cmd.ExecuteReader())
    {
      while (drd.Read())
      {
        // Read from data reader
      }
    }
  }
}

But this is not the case for an OdbcCommand. The parameters in an OdbcCommand are specified by “?” and the sequence of adding parameters is really important unlike to SqlCommand.

using (OdbcConnection con = new OdbcConnection(connectionString))
{
  using (OdbcCommand cmd = new OdbcCommand())
  {
    cmd.Connection = con;
    cmd.CommandText = 
      "SELECT * FROM Employees WHERE FirstName = ? AND LastName = ?";
    // Keep in mind the sequence in which you are adding the 
    // parameters should be same as the sequence they appear 
    // in the query
    cmd.Parameters.AddWithValue("@FirstName", firstName);
    cmd.Parameters.AddWithValue("@LastName", lastName);
    using (OdbcDataReader drd = cmd.ExecuteReader())
    {
      while (drd.Read())
      {
        // Read from data reader
      }
    }
  }
}
C# | Data | MySql

Discussion

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved