Connect Microsoft Access Database in Eclipse [duplicate] - java

Hi I have the below code to connect to MS Access database on Windows 7 OS. I have changed the Data Source short cut to point to 64bit odbc then 32 bit. But still getting the error as
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3072)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at TestDBConnection.main(TestDBConnection.java:21)
And my code is :
import java.sql.Connection;
import java.sql.DriverManager;
public class TestDBConnection {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
System.out.println("filename");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database =
"jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\\Test\\Tests.mdb";
Connection conn = DriverManager.getConnection(database, "", "");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
How ever I have SQL Workbench tool through which I can connect to it but not through java code.
Please need help badly as I am struggling with this from past 3 hours searching on Google.

If your Java app is running in a 64-bit Java Virtual Machine (JVM) then DRIVER={Microsoft Access Driver (*.mdb)} is not going to work because there is no 64-bit version of the Jet database engine. You can...
Download and install the 64-bit version of the Microsoft Access Database Engine from here, and then use DRIVER={Microsoft Access Driver (*.mdb, *.accdb)} in your code.
... or ...
Run your Java app in a 32-bit JVM and continue to use the existing DRIVER= string. The related answer here might prove helpful if you choose this option.
... or ...
Use the UCanAccess JDBC driver for Access databases. It is a free, open-source, pure Java implementation so it works on both 32-bit and 64-bit systems, both Windows and non-Windows. It also works with Java 8 (which has dropped the JDBC-ODBC Bridge). For more details, see:
Manipulating an Access database from Java without ODBC

You can install the 64 ODBC drivers for Access available from Microsoft
http://www.microsoft.com/en-us/download/details.aspx?id=13255

1) you will have to configure System dsn (Driver Microsoft Access Driver(.mdb,.accdb))
2) link .mdb database in above configuration
and write below code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:systemdsnname";
Connection conn = DriverManager.getConnection(database, "", "");

Related

How to connect java to ms access

i am having windows 10 64 bit java 64 bit ms access 64 bit.not i want to connect to java to ms access with jdbc odbc than it show that can not found driver .i do all the task for this but i can not found that driver in my lappi. please anybody help me.
my code is
import java.sql.*;
class driver
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e)
{
System.out.println("Unable to load driver");
e.printStackTrace();
}
}
}
and error is:-
Crash log
The jdbc odbc driver was removed in Java 8 (from the linked Java 7 tech guide) The JDBC-ODBC Bridge should be considered a transitional solution; it will be removed in JDK 8. In addition, Oracle does not support the JDBC-ODBC Bridge. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge. You can use UCanAccess instead.

JDBC not connecting to DB within webservice

I have been working with JDBC. Below is the code I use to obtain connection.
JDBC code:
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
I have generated a Webservice off of a WSDL which contains getters and setters. While it is in the same package of the Webservice (its own class) I can simply run the class and it will generate "Successfully connected". (keep in mind that the build is the same since its in the same package) Now when I insert the code into a method on the Webservice and call it using insert();. From here I invoke the Webservice with the generated client. When looking back at the console I obtain the "com.microsoft.sqlserver.jdbc.SQLServerDriver" error. Which is generally given when paths are not built correct.
It works outside of the getter and setter class, but why not inside?
I have tried to sync a full documentation. It will cover
Various ways of database connection
Sample code for testing connection
Common errors and how we can solve those issues
Define JRE support
How to set the CLASSPATH variable?
How to register the Driver?
How to pass the Connection URL?
Choosing the Right JAR file
Making a Simple Connection to a Database
After installing the Microsoft SQL Server 2000 driver for JDBC, database connection may be done by two ways:
1) with a connection URL, or
2) with a JNDI data source
Sample Code to Test the Connection
The following sample code tries to connect to the database and displays the database name, the version, and the available catalogs. Replace the server properties with the values for your server:
import java.*;
public class Connect{
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "pubs";
private final String userName = "user";
private final String password = "password";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
// Constructor
public Connect(){}
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Connect myDbTest = new Connect();
myDbTest.displayDbProperties();
}
}
If this code is successful, the output is similar to the following:
Connection Successful! Driver Information
Driver Name: SQLServer
Driver Version: 2.2.0022
Database Information
Database Name: Microsoft SQL Server
Database Version: Microsoft SQL Server 2000 - 8.00.384 (Intel X86)
May 23 2001 00:02:52
Copyright (c) 1988-2000 Microsoft Corporation
Desktop Engine on Windows NT 5.1 (Build 2600: )
Avalilable Catalogs
catalog: master
catalog: msdb
catalog: pubs
catalog: tempdb
Basic Connectivity Troubleshooting
Error-1
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Login failed for user 'user'. Reason: Not associated with a trusted SQL Server connection.
Ans:
This error message occurs if the SQL Server 2000 authentication mode
is set to Windows Authentication mode. The Microsoft SQL Server 2000
driver for JDBC does not support connecting by using Windows NT
authentication. You must set the authentication mode of your SQL
Server to Mixed mode, which permits both Windows Authentication and
SQL Server Authentication.
Error-2
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]This version of the JDBC driver only supports Microsoft SQL Server 2000. You can either upgrade to SQL Server 2000 or possibly locate another version of the driver.
Ans:
This error message occurs you try to connect to a SQL Server version
earlier than SQL Server 2000. The Microsoft SQL Server 2000 driver for
JDBC supports connectivity only with SQL Server 2000.
Java Runtime Environment Requirements
Starting with the Microsoft JDBC Driver 4.2 for SQL Server, Sun Java
SE Development Kit (JDK) 8.0 and Java Runtime Environment (JRE) 8.0
are supported. Support for Java Database Connectivity (JDBC) Spec
API has been extended to include the JDBC 4.1 and 4.2 API.
Starting with the Microsoft JDBC Driver 4.1 for SQL Server, Sun Java
SE Development Kit (JDK) 7.0 and Java Runtime Environment (JRE) 7.0
are supported.
Starting with the Microsoft JDBC Driver 4.0 for SQL Server, the JDBC
driver support for Java Database Connectivity (JDBC) Spec API has
been extended to include the JDBC 4.0 API. The JDBC 4.0 API was
introduced as part of the Sun Java SE Development Kit (JDK) 6.0 and
Java Runtime Environment (JRE) 6.0. JDBC 4.0 is a superset of the
JDBC 3.0 API.
For more: System Requirements for the JDBC Driver
To Set the CLASSPATH Variable
The Microsoft SQL Server 2000 driver for JDBC .jar files must be listed in your CLASSPATH variable. The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
Set your system CLASSPATH variable to include the following entries:
\Your installation path\Lib\Msbase.jar
\Your installation path\Lib\Msutil.jar
\Your installationpath\Lib\Mssqlserver.jar
This is an example of a configured CLASSPATH variable:
CLASSPATH=.;c:\program files\Microsoft SQL Server 2000 Driver for
JDBC\lib\msbase.jar;c:\program files\Microsoft SQL Server 2000 Driver
for JDBC\lib\msutil.jar;c:\program files\Microsoft SQL Server 2000
Driver for JDBC\lib\mssqlserver.jar
To Register the Driver
Registering the driver instructs JDBC Driver Manager which driver to load. When you load a driver by using the class.forName function, you must specify the name of the driver. This is the driver name for Microsoft SQL Server 2000 Driver for JDBC:
com.microsoft.jdbc.sqlserver.SQLServerDriver
The following sample code demonstrates how to register the driver:
Driver d = (Driver)Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
To Pass the Connection URL
You must pass your database connection information in the form of a connection URL. This is a template URL for Microsoft SQL Server 2000 Driver for JDBC. Substitute the values for your database:
jdbc:microsoft:sqlserver://servername:1433
The following sample code demonstrates how to specify a connection URL:
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433", "userName", "password");
Choosing the Right JAR file
The Microsoft JDBC Drivers 6.0 and 4.2 for SQL Server provide
sqljdbc.jar, sqljdbc4.jar, sqljdbc41, and sqljdbc42.jar class
library files to be used depending on your preferred Java Runtime
Environment (JRE) settings.
The Microsoft JDBC Driver 4.1 for SQL Server provides sqljdbc.jar,
sqljdbc4.jar, and sqljdbc41.jar class library files to be used
depending on your preferred Java Runtime Environment (JRE) settings.
The Microsoft JDBC Driver for SQL Server 4.0 provides sqljdbc.jar
and sqljdbc4.jar class library files to be used depending on your
preferred Java Runtime Environment (JRE) settings.
Making a Simple Connection to a Database
Using the sqljdbc.jar class library, applications must first register the driver as follows:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
When the driver is loaded, you can establish a connection by using a connection URL and the getConnection method of the DriverManager class:
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;user=MyUserName;password=*****;";
Connection con = DriverManager.getConnection(connectionUrl);
In the JDBC API 4.0, the DriverManager.getConnection method is enhanced to load JDBC drivers automatically. Therefore, applications do not need to call the Class.forName method to register or load the driver when using the sqljdbc4.jar, sqljdbc41.jar, or sqljdbc42.jar class library.
When the getConnection method of the DriverManager class is called, an appropriate driver is located from the set of registered JDBC drivers. sqljdbc4.jar, sqljdbc41.jar, or sqljdbc42.jar file includes "META-INF/services/java.sql.Driver" file, which contains the com.microsoft.sqlserver.jdbc.SQLServerDriver as a registered driver. The existing applications, which currently load the drivers by using the Class.forName method, will continue to work without modification.
Resource Link:
All data's are taken from following-
Using the JDBC Driver
HOW TO: Get Started with Microsoft JDBC
ClassNotFoundException - com.microsoft.jdbc.sqlserver.SQLServerDriver
The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
Check your class path and let me know if that was the issue.
You dont need both jTDS and JDBC in your classpath. Any one is required. You'll most likley need only sqljdbc.jar. Be sure to place it in a psychical location like lib within WEB-INF directory of your project instead of adding it into your classpath via IDE. Reset your service, and trying again. It should fix it self.
Jar file can be found here:
www.java2s.com/Code/JarDownload/sqlserverjdbc/sqlserverjdbc.jar.zip

Connection from a Java program to a SQL Developer database

I would like to access to a Oracle database (SQL Developer) from a Java program. I never used JDBC before.
Here is what i wrote:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:host_name:port:database_name";
Connection con = DriverManager.getConnection(url, login, passwd);
I got an error:
[Microsoft][ODBC Driver Manager]
Data source name not found and no default driver specified
Host name, port, DB name and logins are good.
Is this driver OK to communicate with SQL Developer ?
I don't know what to do,
thanks for helping !
Try this
Class.forName ("oracle.jdbc.driver.OracleDriver");
for Oracle you can use ojdbc
Class.forName("oracle.jdbc.driver.OracleDriver");
for SQL Server u can use jtds
Class.forName("net.sourceforge.jtds.jdbc.Driver");
The JDBC driver sun.jdbc.odbc.JdbcOdbcDriver is bridge driver that wraps an ODBC driver as described here.
SQL Developer is an Oracle tool that acts as an IDE against the Oracle database.
To connect Java to an Oracle database you should obtain the Oracle JDBC driver and ensure the jar is on your classpath (as described in the documentation for java.sql.DriverManager, forcing the class to be loaded is no longer necessary).
The important bit is the connection string, which in its simplest form for Oracle should follow the structure:
jdbc:oracle:thin:#//host:port/service
Where:
host: the hostname of the machine running Oracle
port: the port that Oracle is listening for connections on
service: the database instance to connect to
The full docs are here.

Connecting Java to an MS Access Database without having MS Access installed

I have created a CRUD Application the connecting method of the application is given below. I have tested it on my computer and is working fine, but while tesing on another computer where MS Access is not installed it is throwing NullPointerException.
So what should I do in order to rectify this problem? Are there any libraries for connecting to .mdb files?
These should also run on Linux. I can convert the .mdb file into Open Office Base if Libraries are available...
void DoConnect()
{
try{
String current = new java.io.File( "." ).getCanonicalPath();
current+="\\DataBases\\Quiz.mdb";
String host = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+current+";";
String uName = "";
String uPass = "";
con=new Connection[Size];
stmt=new Statement[Size];
for(int i=0;i<Size;i++)
{
con[i]=DriverManager.getConnection(host, uName, uPass);
stmt[i]=con[i].createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
ts=stmt[0].executeQuery("SELECT * FROM Quiz");
ts.first();
rs=stmt[1].executeQuery("SELECT ANSW FROM Quiz");
System.out.print(rs.getString("STM1"));
}catch (IOException | SQLException err) {
}
}
Are there any libraries for connecting to mdb files ?
Yes, there are. The Jet database engine is included with Windows, but only a 32-bit version is available. If your application is running as a 64-bit process then you'll need to have the 64-bit version of the Access Database Engine (a.k.a. ACE) installed on the machine. You can download the Access Database Engine here:
http://www.microsoft.com/en-us/download/details.aspx?id=13255
Note that to use the Access Database Engine you may have to tweak your connection string to something like...
String host = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+current+";";
...and if that doesn't work on 32-bit machines without the Access Database Engine installed (i.e., machines with just the Jet database engine) then your code may have to
try the Jet connection string first (i.e., your original connection string), and if that fails then
try the ACE connection string (i.e., the one in this answer).
Connecting to Access is not an easy task if you don't have access installed on all client computers .
Moreover Access databases are huge in size .
So I am currently using H2 database which is very easy to use .
Regarding the size , After I copied a 140 Mb Access database to H2 the file was ONLY 732 Kb !
More info can be found here

ODBC Connection Setup in Java

I want to write a Java program that automates the work that the ODBC Data Source Administrator does in Windows.
That is, given an ODBC connection name and a path to the database on the hard drive, I want it to create the connection.
I really have no idea where to even begin with this. I looked at this but it said it was for C and I don't think that's very helpful. If anyone could point me in the right direction for this at all, I would appreciate it.
(I realize this question is REALLY vague, but that's all the information I was given.)
The answer to the question is that you don't need a registered DSN.
Here is an example of using a ODBC connection (not JDBC) from Java, using the system ODBC driver. Instead of editing the registry to create a registered DSN, your alternative is to use a un-registered DSN, like so:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Dir/DB/MyDB.mdb;
Or, using SQL Server:
Driver=sun.jdbc.odbc.JdbcOdbcDriver
Source=jdbc:odbc:Driver={SQL Server};SERVER=127.1;DATABASE=MyDB;UID=sa;PWD=mypass
All ODBC configuration is in Windows registry or odbc.ini in Linux (I haven't used ODBC on other platforms). At first you must create such configuration using ODBC manager, then check what was saved in configuration and write program that do the same. If you work with Windows 32 bit, then check registry at HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
Windows 64 bit have different configurations for 32 bit apps and 64 bit apps (just look for odbc.ini string in registry).
I think Java is not the best language to change something in Windows registry, but with Java you can create .reg text file that can be imported by regedit.exe, or you can use other language like Python with win32 extensions (Active Python has it by default).
You will want to look into using JDBC.
String driver ="sun.jdbc.odbc.JdbcOdbcDriver"
String url = "jdbc:odbc:Driver={Microsoft Access Text Driver (*.txt, *.csv)};DBQ=C:/CSVFolder
query = select * from myfile.csv
Check this one out..
Java Database Connectivity (JDBC) supports ODBC-based databases and provides a independent database.
Connection connection = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("connection string", "userName", "password" );
} catch (SQLException e) {
}
return connection;
I've never had to connect to MS SQL Server before. I've always used DB2 or Derby, MYSQL and everything was always the same for creating a connection. This is what I had to do for SQL Server.
private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
url="jdbc:odbc:;DRIVER={SQL Server};SERVER="+server+","+port+";DATABASE="+dbName;
connection = DriverManager.getConnection(url,user,password);

Categories

Resources