|
I've seen lots of newsgroup posts from people
wanting to connect to Oracle, MySql and Postgres Databases. Fortunately,
there is an ODBC driver for almost every RDBMS system out there, and Microsoft
has made available their ODBC .NET Driver. However, there were at least
2 versions of it before RTM came out, and there seems to be some more
than a little confusion about whether it will "work" with VS.NET
RTM.
The short answer is, yes. You just have
to get the right version of the driver!
So first, let's get the correct animal for
VS.NET 1.0 RTM:
http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml?
Now here is a simplified set of instructions
to get started. Remember, once the ODBC .NET Driver is installed, you
only need the ODBC driver for your database system and you should be able
to connect and use it. Obviously, the connection string will be different
for each RDBMS, but you should have no problem finding examples. Here
we'll just use ODBC to connect to SQL Server on the local machine. It
could be Oracle, MySql, or whatever- the process is the same.
1) Install the ODBC.NET provider.
2) Start a new Windows Application, and
add a DataGrid and a button to the default form.
3) Add a Reference to the Microsoft.Data.Odbc
Assembly:
4) Your "using" statements at
the top of your codebehind should look like the below:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.Data.Odbc;
namespace odbcdriver
5) Double-click on the button you added
in step 2 to add the Click event handler template, and insert the following
code:
private void button1_Click(object
sender, System.EventArgs e)
{
Microsoft.Data.Odbc.OdbcConnection oODBCConnection;
string sConnString ="Driver={SQL Server};Server=(local);Database=Northwind;Uid=sa;Pwd=;";
oODBCConnection = new OdbcConnection(sConnString);
try
{
oODBCConnection.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
string strSQL = "select * from employees";
OdbcDataAdapter da =new OdbcDataAdapter(strSQL, oODBCConnection);
System.Data.DataSet ds = new System.Data.DataSet();
da.Fill(ds,"Employees");
dataGrid1.DataSource=ds.Tables["Employees"] ;
}
6) Run (debug) the application. You should
see the following:
The link below has a Zip file containing
the entire C# Winforms project. Enjoy!
Download
the code that accompanies this article
Peter Bromberg is an independent consultant specializing in distributed .NET solutions
in Orlando and a co-developer of the EggheadCafe.com
developer website. He can be reached at pbromberg@yahoo.com
|