OdbcConnection
This C# connection type is used with MySQL
. It often leads to syntax errors. The connection string does not allow quotes around the values.
With some care this SQL database object in C# programs is effective. We explore the OdbcConnection
objects in the C# language and .NET.
string
If you are using a third-party web host, you will often have a sample connection string. This is useful, but you need to be careful.
MySQL
ODBC 3.51 Driver in curly brackets. This version may be different for your setup.OkieData
, the user name is SamAllen
, and the password is CutiePie
. You can't put quotes around any of the values.DRIVER={MySQL ODBC 3.51 Driver}; SERVER=p50mysq5555.secureserver.net; PORT=3306; DATABASE=OkieData; USER=SamAllen; PASSWORD=CutiePie; OPTION=0;
It is ideal to put your connection string in Web.config in your ASP.NET project. You will have to find the appropriate blocks in the XML config file.
WhateverName
.<!-- This XML should be put in Web.config --> <connectionstrings> <add name="WhateverName" connectionString="Exact string shown above"/> </connectionstrings>
At the top are your using
-statements. Add these two using
-statements at the top. The first adds the database stuff, and the second allows you to access your connection string.
using System.Data.Odbc; using System.Web.Configuration;
We can create an OdbcConnection
by combining it with the using
-statement. The next code block gets our special connection string from the Web.config file.
OdbcConnection
with the identifier "c" is a new connection to the database. These are automatically pooled and shared.// Try to connect to the database based on our stored connection string. string conString = WebConfigurationManager.ConnectionStrings[ "WhateverName"].ConnectionString; using (OdbcConnection c = new OdbcConnection(conString)) { c.Open(); // We are now connected. // Now we can use OdbcCommand objects to accomplish things. }
MySQL
Here we declare a new OdbcCommand
object, add a parameter to the command object, and then read in data from the database. Note the question mark in the command text.
OdbcCommand
takes the connection object as the second parameter. The paramWord
string
is added to the command.var
" but that is not important. The parameter is added in the first question mark.MagicKey
column is equal to paramWord
.using (OdbcCommand c = new OdbcCommand("SELECT ColumnWord FROM OkieTable WHERE MagicKey = ?", con)) { c.Parameters.AddWithValue("@var", paramWord); using (OdbcDataReader reader = c.ExecuteReader()) { while (reader.Read()) { string word = reader.GetString(0); // Word is from the database. Do something with it. } } }
Here we fixed bugs with OdbcConnection
. This can be applied to any ADO.NET provider, from SqlConnection
objects to SqlCeConnections
and SQLiteConnections
.