ODBC Programming in CShape
ODBC Programming in CShape
ODBC Programming in CShape
Web: http://devmentor.org
Email: [email protected]
Perquisites
I am going to assume you already have install MySQL on your system along with the
ODBC driver from www.mysql.org
You should also know basic SQL and be able to create and populate your own database
tables. A quick premier on SQL can be found at: www.w3schools.com/sql/default.asp
Creating a Database
Bring up MySQL Query Browser and type and execute the following commands.
use store
c) We will create a database table with the following schema: fruits( name, cost )
1. Before you can start using the ODBC class definitions, you will need to include the
right module.
Each ODBC name/value pare is separated with a ';' semicolon. There should be no spaces
between the '=' equal sign and the name and value.
The "DSN" setting defines the name of the ODBC Data Source to connect to.
The "UID" ODBC connection string defines the "User ID"
The "PWD" ODBC connection string define the "Password"
On the following page we will setup the ODBC Data Source, this is what our C#
application will use when connecting to our database.
To create a new Data Source, you will need to click on the “Add” button and then find
“MySQL” in the list of available Data Sources.
Before clicking on the "OK" button, you should click the "Test" button to verity that you
are able to connect to the database. Make sure that the MySQL database service is
running first. If everything is correct then you will see the following dialog box after
clicking on the "Test" button.
dbMySQL.Open();
dbMySQL.Close();
}
catch(OdbcException e)
{
Console.WriteLine("Database Error\n\n{0}", e.ToString());
}
finally
{
if(dbMySQL != null) dbMySQL.Close();
}
We need to make sure to close the connection once we are done, otherwise the
connection will remain open even after the object goes out of scope.
4. After we have attained a open database connection, we need to get the command object
in order to execute our SQL.
6. Since this SQL statement will be returning a result table we need to call the
ExecureReader( ) method on the OdbcCommand object "sqlCommand".
7. Once we have a data reader object, we can begin to read in the row value one at a time
using the Read( ) method. This method will return 'true' if there are more rows to be
fetched, and 'false' when there are no more rows existing in the result table.
9. Once we are done we need to make sure to close the OdbcCommand and
OdbcDateReader objects. Since OdbcCommand does not have a close method, you
will need to call it's Dispose( ) method.
namespace csMySQL
{
class Program
{
static void Main(string[] args)
{
// prepare ODBC database connection
string strConnect = DSN=MySQL;UID=root;PWD=admin;DATABASE=store";
// execute sql
sqlCommand.CommandText =
"select * from fruits order by cost";
Console.Write(("").PadRight(11, '-'));
Console.Write(" ");
Console.WriteLine(("").PadRight(11, '-'));
}
}
}