Escolar Documentos
Profissional Documentos
Cultura Documentos
O ODBC .NET Data provider permite o acesso a banco de dados ODBC através de
um driver ODBC nativo da mesma forma que os provedores nativos OLE DB. A
grande vantagem em usar os provedores ADO.NET é que todos eles definem a
mesma hierarquia de classes , e , por isso a única coisa que você tem que alterar
são as classes e a string de conexão.
Após instalar o OBDC .NET temos que customizar a barra de ferramentas (toolbox)
para incluir os componentes de dados ODBC. Vamos fazer isto:
Pronto , agora basta inserir o código que trata as informações da fonte de dados e
fazer a referência no código da classe do OBDC:
Imports Microsoft.Data.Obdc
Obs: Você pode usar um DSN - ODBC Data Source - como uma string de
conexão através do Administrador ODBC.
Ex: conexão = New
OdbcConnection("DSN=DADOS;UID=Macoratti;pwd=Teste")
Vou mostrar como acessar um banco de dados MySQL usando o provedor ODBC
.NET. Se você ainda não tem o MySQL instalado você pode fazer o download de
uma das versões disponíveis no link :
http://www.mysql.com/downloads/index.html . A instalação é simples basta
descompactar e seguir as instruções .
Considerando que seu MySql esta instalado vamos agora criar um banco de dados
com o nome de Clientes no MySql e neste banco de dados vamos criar a tabela
Clientes e inserir alguns dados. Para facilitar o nosso serviço vamos usar uma
ferramenta free para fazer este serviço: DBtools Manager , que você pode pegar
em : http://www.dbtools.com.br/EN/
Nota: No link : http://www.mysql.com/downloads/api-dotnet.html você pode
pegar o driver MySQL para usar na plataforma .NET ( veremos isto em outro
artigo.)
Criado o banco de dados vamos usar o Table Editor para criar uma nova
tabela , chamada Clientes , e definir a sua estrutura conforme abaixo :
A próxima etapa é inserir alguns dados na tabela Clientes , conforme figura
abaixo:
Bem , já temos o banco de dados , a tabela com os dados , só falta agora criar um
projeto no VS.NET , e, usando o VB.NET fazer uma conexão via ODBC .NET para
exibir os dados em um controle ListBox. Vamos lá...
Obs: O acesso a dados via ODBC é mais lento do que usar um provedor nativo Ole
DB. Somente o utilize se não tiver alternativa.
referências:
HOW TO: Use the ODBC .NET Managed Provider in Visual Basic .NET and
Connection Strings
On This Page
• SUMMARY
o Troubleshooting
• REFERENCES
SUMMARY
This step-by-step article describes how to use the ODBC .NET Managed Provider in Visual Basic
.NET. This article also includes samples connection strings that you can use to access your data.
The ODBC .NET Data Provider is an add-on component to the Microsoft .NET Framework Software
Development Kit (SDK). It provides access to native ODBC drivers the same way that the OLE
DB .NET Data Provider provides access to native OLE DB Providers. Although the ODBC .NET Data
Provider is intended to work with all compliant ODBC drivers, it has only been tested with the
following drivers:
NOTE: If the .NET Framework SDK (which is included with Visual Studio .NET) is not installed, the
setup for this download fails. As part of the setup for this download, the Microsoft.Data.ODBC
namespace is added to the Global Assembly Cache by using the Gacutil.exe utility that is included
1. Download the ODBC .NET Managed Provider from the following Microsoft Web site:
http://www.microsoft.com/downloads/details.aspx?familyid=6ccd8427-1017-4f33-a062-
d165078e32b1
2. The ODBC .NET Data Provider also requires that you install Microsoft Data Access
Components (MDAC) version 2.7 or later. You can download the latest version of MDAC
http://msdn.microsoft.com/en-us/data/aa937729.aspx
3. After you install the ODBC .NET Data Provider, proceed to the next section to create the
project.
2. Create a new Visual Basic Windows Application project. Form1 is added to the project by
default.
5. Switch to Code view, and add the following code immediately before the Public Class
Form1 code:
6. Imports System.Data
7. Imports Microsoft.Data.ODBC
8. Add four Button controls to Form1, and label these controls SQL Server, Jet, Oracle
2. Dim cn As OdbcConnection
3. cn = New OdbcConnection("DRIVER={SQL
Server};SERVER=MySQLServer;UID=sa;" & _
4. "PWD=mypassword;DATABASE=northwind;")
5.
6. Dim mystring As String = "select * from Customers"
7. Dim cmd As OdbcCommand = New OdbcCommand(mystring)
8. cn.Open()
9. MsgBox("Connected")
10. cn.Close()
2. Click each button. A message box appears, which states that you have successfully
Troubleshooting
If you encounter a problem when you connect to your data source (for example, if you use an
incorrect password, User ID, or database name), you receive the following generic error message
To provide more information about the error and to assist in troubleshooting, you can add a try-
Try
cn.Open()
Catch ex as OdbcException
MsgBox(ex.Message)
Finally
cn.Close()
End Try
REFERENCES
For more information, click the following article number to view the article in the Microsoft
Knowledge Base:
For more information about .NET managed providers, refer to the .NET Developer's Center or the
http://msdn.microsoft.com/en-us/library/ms810268.aspx
For more information about .NET, visit the .NET newsgroups. The
APPLIES TO