I am trying to connect to MS Access database from my Java application. This is my code:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "UserInformation.accdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Statement st= con.createStatement();
int i=st.executeUpdate("insert into Users(User_Name,User_Password) values('"+username+"','"+password+"')");
System.out.println("Row is added");
}catch (Exception e) {
System.out.println("Error: " + e);
}
I get this exception: Data Source Name Not Found And No Default Driver Specified (ODBC)?
How can I fix it?
Thanks in advance
It can be several things. I encountered this problem in hacking a database from a 32-bit machine on my 64-bit desktop.
If you google issues using odbc with 32 vs 64 bit in Java you will see a good amount of material. What ultimately worked for me was switching from Java 5 to 6 and making sure my Eclipse runtime configurations were not setting an incompatible bit-mode.
Sorry for being a bit vague, but after spending a few hours trying to figure out I believe it can be very situational dependent.
Related
I’m trying to connect a Java program to a remote Oracle DB. After doing some research online, I decided that the easiest way to do this was with the Oracle JDBC driver. I downloaded and ran the jar file and got the message “***** JCE UNLIMITED STRENGTH IS INSTALLED *****.” The problem is that when I try to add the driver to my classpath (javac -classpath ojdbc8.jar Connect.java), I keep getting an error message saying “package oracle.jdbc.driver does not exist.” I’ve been researching how to fix this online, but I’m only getting confused. Any ideas on what I did wrong?
import java.sql.*;
public class Class1 {
public static void main (String args [])
throws SQLException
{
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to the database
// You must put a database name after the # sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as `<host>`:`<port>`:`<sid>`. The example uses the short cut syntax.
Connection conn =
DriverManager.getConnection ("jdbc:oracle:thin:hr/hr#myhostname:1521:orcl",
"myUsername", "myPassword");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP");
// Iterate through the result and print the employee names
while (rset.next ())
System.out.println (rset.getString (1));
conn.close(); // ** IMPORTANT : Close connections when done **
}
}
The error is:
java: package oracle.jdbc.driver does not exist
Can you try to run the sample DataSourceSample.java? Make sure you have the JDBC driver in the classpath. You can also refer to this quickstart for detailed instructions.
I am working on an JAVA app that evaluates the data and log sizes of all databases on an instance and mails a monthly report. I am currently working with SQLServer2014. I am using an SQL query that calculates the size of all databases by querying sys.master_files.
The problem is that when using JDBC to make the query, it returns the error:
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost"
I have tried connecting to particular databases and that works fine. Is there any way to do this query directly to sys.master_files using JDBC? Or is there a smarter way altogether to accomplish the same result?
Thanks
Your "No suitable driver found" error is simply due to a malformed connection URL. jdbc:microsoft:sqlserver is not valid.
As for connecting to an instance without specifying a particular database, this works fine for me:
// NB: no databaseName specified in the following
String connectionUrl = "jdbc:sqlserver://localhost;instanceName=SQLEXPRESS;integratedSecurity=true";
try (Connection conn = DriverManager.getConnection(connectionUrl)) {
String sql = "SELECT name FROM sys.master_files WHERE type_desc='ROWS' ORDER BY database_id";
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Note that sys.master_files is a system view that is available in all databases, so AFAIK it doesn't matter what the current database (catalog) is when you call it.
I am using eclipse and java to connect to an oracle 12c database. But every time I run through the process, I get a connection fail error that reads:
java.sql.SQLException: Invalid Oracle URL specified
Here is what my code looks like:
import java.sql.*;
public class JdbcConnection {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin#localhost:1521:xe", "username", "password");
Statement statement = con.createStatement();
String sql = "select * from employees";
ResultSet rs = statement.executeQuery(sql);
while (rs.next())
System.out.println(rs.getInt(3) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am using a windows 7 sp1 Ultimate (64 bit)
CPU: i5 2.85 ghz
RAM: 8GB
Oracle is installed in a separate hard drive (in the same computer).
EDIT:I have tried the first suggestion from this post: How do you find out the Oracle database's URL?
and I get an error that says:
ORA-00928: SELECT KEYWORD MISSING...
This error occurs when I run the oracle "SQL DEVELOPER" application on the startup menu and type the suggestions from post above.
Note: I want to connect to the database from eclipse and query it programatically.
Is there a way to find out what the correct connection URL is?
Please help.
I have a Jbutton (GetDataFromDB) in a simple java application that is suppose to load the data from the database depicted in the path in the code below into a Jtable in the application.
Edited answer into code:
private void GetDataFromDBActionPerformed(java.awt.event.ActionEvent evt) {
Connection con;
ResultSet rs = null;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={MS Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
stmt = con.createStatement();
String query = null;
query = "select * from cost";
rs = stmt.executeQuery(query);
i = 0;
while (rs.next()){
i = i + 1;
jTable.getModel().setValueAt(rs.getString(1), i, 1);
jTable.getModel().setValueAt(rs.getString(2), i, 2);
}
rs.close();
stmt.close();
con.close();
} catch(Exception err){
System.out.println(err.getMessage());
}
}
When I press the button I get the following message in the run output window:
No suitable driver found for jdbc:odbc:Driver={Microsoft Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I have at the top of my code the import:
import java.sql.*;
I have also tried changing from "Microsoft Access Driver" to "MS Access Driver" but I get the same message in the run output window i.e.
No suitable driver found for jdbc:odbc:Driver={MS Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I'm really thankful for all your help, input and feedback.
Depending on the driver and If you are pre JDK 6**!
You need to register the driver.
Try adding:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
So:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
It's also worth mentioning you don't need to do this every time you get a connection, just once to make sure the class is loaded.
There are a lot of stackoverflow questions relating to this, but the reason for it is below:
Source - From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to
initialize your JDBC driver by calling the method Class.forName. This
methods required an object of type java.sql.Driver. Each JDBC driver
contains one or more classes that implements the interface
java.sql.Driver. ... Any JDBC 4.0 drivers that are found in your class
path are automatically loaded. (However, you must manually load any
drivers prior to JDBC 4.0 with the method Class.forName.)
On a related and very important note.
I would also recommend looking up how to handle connections. External Resources like database connections and cursors are easy to leak if you are not familiar with them. Look up 'try finally blocks', or more recently in java 7+ 'try-with-resources'.
I'm currently looking to write an importer in my Java program to import data from a file which contains a JET database, but so far searching for a JDBC driver for this format (or just another Java library which can read from it) has proved fruitless.
Does anyone know if such a driver exists, or if not what (platform independent) alternatives might be available?
I actually have been importing CSV files into Access database using JDBC and jetEngine query like this
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "C:/Automation_Tools/Databases/Data.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= fileName.trim() + ";DriverID=22;READONLY=false}";
// add on to the end now we can get the connection from the DriverManager
con = DriverManager.getConnection( database ,"","");
and then using query like this
String sql = "INSERT INTO " + accessTableName + " SELECT * FROM [Text;HDR=YES;TextDelimiter=\";Has Quotes=TrueFMT=Delimited(,);DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
//Import/create table
String sql = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;TextDelimiter=\";FMT=Delimited(,);DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
`
I am just now researching this myself and am going to try out UCanAccess. According to the main page it says that it is
an open source Java JDBC Driver implementation which allows Java developers and jdbc client programs (e.g., DBeaver, NetBeans, SQLeo, Open Office Base, Libre Office Base, Squirrell) to read/write Microsoft Access database.
Because it is a pure java implementation it run in both Windows and non-Windows Operative Systems(e.g., linux/unix). No ODBC needed.
You can use the built in JDBC ODBC bridge driver.
Use a connection string like: jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=database.mdb.
This is not platform independend. The Jet engine (or ACE) has to be installed. Sometimes there are problems with encoding and Memo fields.
There is an alternative: http://www.hxtt.com/access.html
They claim platform independence but I didn't try it myself.