This question already has answers here:
Replacement for JDBC-ODBC Bridge
(2 answers)
JDBC ODBC Driver Connection
(2 answers)
Closed 10 months ago.
I am developing a Spring Boot application that polls data from a legacy ODBC data source and inserts it into a MS SQL Server database.
I need to connect to DSN that is using Progress OpenEdge driver.
My R&D code to connect to DSN looks like this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcDemo
{
public static void main(String args[]) throws Exception
{
try
{
String query = "SELECT Name,Description,Qty,Cost FROM Stock";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DSN_Name");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String name = rs.getString("Name");
String desc = rs.getString("Description");
int qty = rs.getInt("Qty");
float cost = rs.getFloat("Cost");
System.out.println(name + ", " + desc + "\t: " + qty + "\t# $" + cost);
}
con.close();
}
catch (Exception e)
{
System.err.println(e);
}
}
}
But it throws java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver error when run. I did some Googling and found this is no longer supported. How can then I connect to this ODBC data source? I am using Java 17.
java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver
exception comes in Java 8 because it has removed the JDBC ODBC bridge
driver class "sun.jdbc.odbc.jdbcodbcdriver" from JDK and JRE. This
class is required to connect any database using Object database
connectivity driver e.g. Microsoft Access, but unfortunately, you
cannot use it from JDK 8 onward. In order to solve this error, just
use the Jackcess library or a commercial driver like HXTT. Normally,
in pre-Java 8 world, java.lang.classnotfoundexception
sun.jdbc.odbc.jdbcodbcdriver error comes when you try to connect to
the Microsoft Access database from Java using JDBC and JDBC ODBC
bridge driver is not available in the classpath.
Read more:
https://javarevisited.blogspot.com/2015/07/how-to-solve-javalangclassnotfoundexception-sun.jdbc.odbc.jdbcodbcdriver.html#ixzz7TTDxvBZp
We can still use JDBC-ODBC Bridge in Java 8 (Java 17 not tested) too, we can always pull the driver from JDK 7: Removal of JDBC ODBC bridge in java 8
Related
Java Tutorial says there are 2 ways to connect to database thru JDBC: with DriverManager class (old, not recommended) and with DataSource class.
I undestand how to do it with DriverManager:
Connection con = DriverManager.getConnection("jdbc:sqlite:mytest.db");
...
But I cannot find how to use DataSource for SQLite thru JDBC. Does SQLite (or JDBC driver providers for it, I don't know how to call it correctly) support using DataSource at all?
I am using xerial/sqlite-jdbc driver to use SQLite from java (https://github.com/xerial/sqlite-jdbc)
My best guess is that I shall use org.sqlite.SQLiteDataSource class (it comes in sqlite-jdbc-3.15.1.jar for Xerial sqlite-jdbc driver), but how? And is it so? I also guess, that how to do it shall be in Xerial driver docs, but they give only example of how to connect using DriverManager.
So I am asking kind help of guru to confirm that this Xerial driver/jar doesn't support DataSource syntax, or to give example how to do it, or to suggest alternative driver with DataSource support (for SQLite from Java), or advice otherwise...
Java Tutorial
JDBC Driver Manager — The JDBC DriverManager class defines objects
which can connect Java applications to a JDBC driver. DriverManager
has traditionally been the backbone of the JDBC architecture. It is
quite small and simple.
The Standard Extension packages javax.naming and javax.sql let you use
a DataSource object registered with a Java Naming and Directory
Interface™ (JNDI) naming service to establish a connection with a data
source. You can use either connecting mechanism, but using a
DataSource object is recommended whenever possible.
My best guess is that I shall use org.sqlite.SQLiteDataSource class (it comes in sqlite-jdbc-3.15.1.jar for Xerial sqlite-jdbc driver),
Yes, that seems likely.
but how?
I just tried the following and it worked for me:
package com.example.sqlite.sqlite_test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.sqlite.SQLiteDataSource;
public class SqliteTestMain {
public static void main(String[] args) {
SQLiteDataSource ds = new SQLiteDataSource();
ds.setUrl("jdbc:sqlite::memory:");
try (Connection conn = ds.getConnection()) {
System.out.println("Connected.");
String sql =
"SELECT COUNT(*) AS n FROM \"sqlite_master\"";
try (
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql)) {
rs.next();
System.out.printf(
"The \"sqlite_master\" table contains %d row(s).%n",
rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
}
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.
This question already has an answer here:
The specified DSN contains an architecture mismatch Error
(1 answer)
Closed 8 years ago.
A program to retrive records from database
import java.sql.*;
import javax.sql.*;
public class Database
{
public static void main(String a\[\])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn =DriverManager.getConnection("jdbc:odbc:data");
Statement st=cn.createStatement();
ResultSet rs= st.executeQuery("select * from student ");
while(rs.next())
{
int r=rs.getInt(1);
String n= rs.getString(2);
int m=rs.getInt(3);
System.out.println("Roll Name Marks");
System.out.println(r+" "+n+" "+m);
}
cn.close();
}
catch(Exception e)
{
}
}
}][1]
I am running 64 bit Windows 7
Created the DSN from sysWOW64 folder
Have a database consisting of 3 fields Roll Name Mark
After Compiling no errors are found
Executing the program results in no Output
Why I am not able to Execute the program
![At command line no output][1]
Edit from comments
The exception I am getting is
SQLException: [Microsoft][ODBC Driver Manager] The specified DSN contains an architecture mismatch between the Driver and Application
Based on this error:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] The specified DSN contai ns an architecture mismatch between the Driver and Application
The problem is your Java architecture is probably 64-bits based but when you accessOdbcad32.exe through this path:
%windir%\SysWoW64\odbcad32.exe
You're actually accessing the 32-bits version of the ODBC controller. Consequently you have architecture mismatch issues. Check this answer for more details.
To make it work you must be sure Java, DSN and MS ODBC driver are all the same architecture either 32 or 64 bits.
So you can:
Download a 32-bits JDK and leave the DSN you already have.
Access the DSN directly from %windir%\System32 folder (is the
64-bits version) and create the data source there.
When you receive no Java exception/error and no output, it seems you can connect to the database and it simply doesn't contain any data.
i am trying to execute a sql command from a java program..i dont have any errors regarding this code..but i am facing connection refusals from the database..
import java.sql.*;
public class DBCreateTable
{
public static void main(String args[]) throws Exception
{
DriverManager.registerDriver (new Oracle.jdbc.driver.OracleDriver());
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","lms","abc");
Statement stmt=con.CreateStatement();
stmt.executeUpdate("create table emp(eno number(5),name varchar2(20))");
}
}
the errors encountered are:
Exception in thread "main" java.sql.SQLException: Io exception: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=185599488)(ERR=12505)(ERROR_STACK=(ERROR=(CODE=12505)(EMFI=4))))
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:333)
at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:404)
at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.ja
va:468)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:314)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at DBCreateTable.main(DBCreateTable.java:7)
In my sql commands i have done the following..
SQL> connect system/tiger;
SQL> create user lms identified by abc;
SQL> grant connect,resource to lms;
and plz tell me what is scott tiger..i am messing a lot there..what users are there..what to unlock and how?? plz thanks..
Add an oracle driver jar to the project build path, and it should work.
(eg. http://mirrors.ibiblio.org/pub/mirrors/maven/mule/dependencies/maven1/oracle-jdbc/jars/ojdbc14.jar)
Your package name is wrong.
DriverManager.registerDriver (new **Oracle**.jdbc.driver.OracleDriver());
In java, package name always start by uncapitalize letter. Your program failed in compilation time.
The oracle.jdbc.driver.* classes, theojdbc4.jar file, and theOracleConnectionCacheImpl class are no longer supported or available from Oracle 11g onwards. So use oracle.jdbc.oracledriver instead.
karjala
did you dowload Oracle JDBC Drivers first download them, You can download Oracle JDBC drivers from here
http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html
Choose the version appropriate for your database version.
Java Program to Connect to Oracle:
The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle’s built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.
1 // Example Java Program - Oracle Database Connectivity
2
import java.sql.Connection;
3
import java.sql.Date;
4
import java.sql.DriverManager;
5
import java.sql.ResultSet;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
9
public class OracleSample {
10
11
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:XE";
12
public static final String DBUSER = "system";
13
public static final String DBPASS = "manager";
14
15
public static void main(String[] args) throws SQLException {
16
17
// Load Oracle JDBC Driver
18
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
19
20
// Connect to Oracle Database
21
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
22
23
Statement statement = con.createStatement();
24
25
// Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
26
// Enables us to retrieve values as if querying from a table
27
ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
28
29
30
if (rs.next()) {
31
Date currentDate = rs.getDate(1); // get first column returned
32
System.out.println("Current Date from Oracle is : "+currentDate);
33
}
34
rs.close();
35
statement.close();
36
con.close();
37
}
38
}
i hope this will help you guys....... :-)
I'm trying to get insert ID while after inserting some data in my database.
String sql = "INSERT INTO ADI.DUMMY(dummy_data) VALUES('from database logger')";
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int extUptReturn = ps.executeUpdate(sql);
But I got this exception:
Java exception: ''java.lang.UnsupportedOperationException'';
thrown from class name: ''sun.jdbc.odbc.JdbcOdbcConnection'', method name: ''prepareStatement'', file: ''JdbcOdbcConnection.java'', line: '1762'
The ODBC bridge driver doesn't support it. Nothing to do against. Either replace the driver or live with it. I would just use a real JDBC driver instead of the poorly-developed, feature-lacking, bug-rich Sun ODBC bridge driver. Almost all self-respected server based RDBMS vendors provides a fullworthy JDBC driver for download at their homepage. Just Google "[vendorname] jdbc driver download" to find it. Here's an overview:
MySQL JDBC driver
PostgreSQL JDBC driver (note: older versions didn't support generated keys as well).
Oracle JDBC driver (note: older versions didn't support generated keys as well).
MSSQL JDBC driver (or performancewise better, the jTDS JDBC driver)
DB2 JDBC driver is hard to find in IBM's online forest, but it's usually already included in the /java folder of the DB2 installation.
UCanAccess driver for Microsoft Access databases (more details here).
MAy be the JDBC implementation could not be supporting the sepcific opration.
CHeck the JDBC driver used.
Try this example instead of Statement.RETURN_GENERATED_KEYS:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection
.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BRANCHID is the auto generated id