在 Java 中为 MS Access 创建无 DSN 连接
我正在构建一个需要与 MS Access 数据库通信的桌面应用程序.现在,除非我想在每台将使用桌面应用程序的计算机上为数据库注册 DSN,否则我需要一种以无 DSN 的方式连接到数据库的方法.
I'm building a desktop app that needs to communicate with a MS Access database. Now, unless I want to register the DSN for the database on every computer that's going to use the desktop app, I need a way to connect to the database in a DSN-less fashion.
我搜索了很多,找到了一些关于如何创建连接字符串的有用链接a> 基于此,我尝试基于此修改我的程序,但没有成功.下面的代码失败.如果我将 getConnection 中的字符串切换为jdbc:odbc:sampleDB",它会起作用,但那是使用 DSN 而不是我想要实现的.
I've searched alot and found some useful links on how to create connection strings and based on that I tried modifying my program based on that but without success. The code below fails. If i switch the string in the getConnection to "jdbc:odbc:sampleDB" it works, but that's using DSN and not what I want to achieve.
如何在 java 中编写和使用连接字符串来建立到 MS Access 数据库的无 DSN 连接?
private Connection setupConnection() throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Driver={Microsoft Access Driver (*.mdb)} &_ Dbq=c:\as\sampleDB.mdb");
return con;
}
另外:我还想指出,如果有人知道通过 DSN 连接实现我所要求的方法,我会很乐意倾听!
Addition: I'd also like to point out that if anyone has an idea of a way to achieve what I asked for WITH a DSN-connection I'll gladly listen to it!
JDBC 连接字符串应该以 jdbc:
开头,例如:
JDBC connection string shouls start with jdbc:
like:
jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\Nwind.mdb
所以试试:
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=c:\as\sampleDB.mdb");
如果您配置了 DSN,那么您可以使用更简单的连接字符串连接到它:jdbc:odbc:[alias]
,例如:
If you configure DSN then you can connect to it using simplier connect string: jdbc:odbc:[alias]
, example:
jdbc:odbc:northwind