使用 vb.net 中的代码创建到 ODBC 数据源的连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20716944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:13:07  来源:igfitidea点击:

Creating Connections to ODBC Data Sources using codes in vb.net

vb.netvisual-studio-2010.net-4.0

提问by har07

I am trying to connect using vb.net (Visual studio 2013) to an MS Access Database 2007(.accdb) using codes. But something is wrong in my code and i can't figure it out.

我正在尝试使用代码将 vb.net (Visual Studio 2013) 连接到 MS Access Database 2007(.accdb)。但是我的代码有问题,我无法弄清楚。

the Database name is "localDatabase.accdb"

数据库名称是“localDatabase.accdb”

I didn't put any password on my database

我没有在我的数据库上设置任何密码

I'm using a 64bit

我正在使用 64 位

Thanks in advance!

提前致谢!

Here is my code:

这是我的代码:

Module Module1
Dim conn As New System.Data.Odbc.OdbcConnection
Public Sub ConnectToOdbc()

    conn.ConnectionString = Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"

    Try
        conn.Open()
    Catch ex As Exception
        MessageBox.Show("Failed to connect to data source")
    Finally
        conn.Close()
    End Try

End Sub

End Module

回答by AdorableVB

this is just a hypothesis..
I am using ACE 12.0 now on my app, and it works fine. the different thing is the code try to use this..

这只是一个假设。
我现在在我的应用程序上使用 ACE 12.0,它运行良好。不同的是代码尝试使用这个..

Imports System.Data.OleDb
'instead of obdc
con = New OleDbConnection
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & Path.Combine(Application.StartupPath, "YourDatabase.accdb")
'put your .accdb in your app folder

maybe the error is it can't find your .accdb file.

也许错误是它找不到您的 .accdb 文件。

回答by har07

Change this line:

改变这一行:

conn.ConnectionString = Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"

to this:

对此:

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MyPc\Documents\Visual Studio 2013\Projects\database\localDatabase.accdb"

ConnectionString as the name tell is a string, so you need to wrap it with double-quotes to be recognized as string by VB compiler.

ConnectionString 顾名思义就是一个字符串,所以需要用双引号括起来才能被VB编译器识别为字符串。

UPDATE :

更新 :

Also you need to change the connection object from Odbc to OleDb:

您还需要将连接对象从 Odbc 更改为 OleDb:

Dim conn As New System.Data.OleDb.OleDbConnection