To connect to MySQL database you can use the System.Data.Odbc namespace in .net
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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 } } } } |