java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver when using Maven Dependency - java

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>7.0.47</version>
</dependency>
Above is the maven dependency I'm using.
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#//ip:port:ora11g");
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("un");
p.setPassword("pw");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
try {
con = datasource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from user");
int cnt = 1;
while (rs.next()) {
System.out.println((cnt++)+". Host:" +rs.getString("Host")+
" User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
}
rs.close();
st.close();
} finally {
if (con!=null) try {con.close();}catch (Exception ignore) {}
}
And above is my database querying test code snippet.
When I'm executing the program I'm getting "java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver" exception.
I searched for the issue and read that I have to "make sure oracle jdbc jar is in the classpath". I'm not sure why do I have to set it manually or is it actually required.

Use below dependency
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
and use below code to connect with your oracle database.
Class.forName("oracle.jdbc.OracleDriver");
String dbURL1 = "jdbc:oracle:thin:{USER}/{PASSWORD}#{URL}:{PORT}:{DBNAME}";
//e.g. String dbURL1 = "jdbc:oracle:thin:tiger/scott#localhost:1521:productDB";
Connection conn1 = DriverManager.getConnection(dbURL1);
if (conn1 != null) {
System.out.println("Connected with connection #1");
}

I resolved the issue by adding the corresponding ojdbc.jar to the project.
It can be resolved by adding the mentioned maven dependency too (mentioned by Joy).

Note that you can download the 19.3 JDBC drivers from central maven

Related

Error while connecting to Cloud SQL using jdbc driver

I have written a basic java code to connect to my Cloud SQL instance. I have added the mysql jar connector in this project.
import java.sql.*;
class MysqlCon {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://project-name:us-central1:test-instance", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from testing");
while (rs.next())
System.out.println(rs.toString());
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am unable to connect and receiving this exception
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "us-central1:test-instance"'.
Any help is highly appreciated.
Thanks!
Thanks nbk for your comment. I was able to solve the issue by modifying the connection string and including this dependency in my maven project
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.15</version>
</dependency>
Updated connection string
"jdbc:mysql:///testing?cloudSqlInstance=project-name:us-central1:test-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=username&password=password"

Java, Maven, connect SQL , no suitable driver

I am building a project using Netbeans IED, with java. The project is using maven and I am attempting to connect it to sql database which I am having issue's. The code works in java but not with maven.
Here the error:
No suitable driver found for jdbc:derby://localhost:1527/Database
Java Code:
public class DatabaseTest {
public static Connection ConnectionObj = null;
public static Statement SqlStatement = null;
public static ResultSet Sqlresult = null;
public static ResultSetMetaData MetaData = null;
public static String query = "Select * from Wallet";
public static String url = "jdbc:derby://localhost:1527/Database";
public static String user = "ABM";
public static String pass = "password2";
public static void main(String[] args) {
try {
//Allows you to connect the database
ConnectionObj = DriverManager.getConnection(url, user, pass);
SqlStatement = ConnectionObj.createStatement();
Sqlresult = SqlStatement.executeQuery(query);
MetaData = Sqlresult.getMetaData();
System.out.println("Connection worked");
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Prom depency's:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
</dependency>
https://gyazo.com/8937aada3bd4a8f5b108b5dc9b386dd7
This part of your POM file is incorrect:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
Your program is attempting to use JDBC to connect to a Derby database, so you should be using a Derby JDBC driver, not a MySQL JDBC driver.
Replace the above with the following:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.14.1.0</version>
</dependency>
(Use the same version as your main Derby version ...)
The code works in Java but not with Maven.
Curious. Perhaps you are setting the runtime classpath correctly in the Java case.

SQL Server Java driver not working in class path

I have written a simple Java file to handle some SQL that is integrated with SQL server.
I downloaded the appropriate driver and stored the JAR in the correct class path however it only works if I run the file directly.
I have tried calling methods within the sql class from another class and i get the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
I understand that this issue is well documented but it doesn't address my unique problem which is that it works within the file but not externally.
Another issue is that after the program is closed and rebuild my program forgets that the JAR was added as a library and requires me to add it again which is not good.
I have tried adding the class path by manually copying and pasting it into an XML config file but this is a hacky solution and I would rather do it properly. Please let me know where I am going wrong.
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.ow2.asm/asm/5.0.4/da08b8cce7bbf903602a25a3a163ae252435795/asm-5.0.4.jar!/" />
<root url="jar://$USER_HOME$/IdeaProjects/r3prototypingCFS/contracts/src/main/kotlin/com/r3corda/protocols/sqljdbc42.jar!/" />
</CLASSES>
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Use jdts driver ..it work with Sql Server 2014.
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
and src
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException {
// write your code here
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/DATABASENAME";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "username";
String password = "yourpassword";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
Statement stmt = conn.createStatement();
String sql = "SELECT top 10 PhoneNumber,RegistrationDate\n" +
" \n" +
" FROM tblProductRegistration";
// ResultSet resultSet = stmt.executeQuery(sql);
// String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
//Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
// preparedStatement.setInt(1, 1001);
// ResultSet resultSet = preparedStatement.executeQuery( );
//STEP 5: Extract data from result set
while(resultSet.next()){
//Retrieve by column name
String PhoneNumber = resultSet.getString("PhoneNumber");
String RegistrationDate = resultSet.getString("RegistrationDate");
//Display values
System.out.print("PhoneNumber: " + PhoneNumber);
System.out.print("RegistrationDate: " + RegistrationDate);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}

How to connect to Neo4j 3.0 database with neo4j-jdbc?

Hi,
I've created a maven project in eclipse and added the dependency:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc</artifactId>
<version>3.0</version>
</dependency>
I'm just trying to get a connection to my db working so that I can move on to integrate the connection with my main project but I'm having trouble getting things off the ground.
I've used the code example given on the official repo:
import org.neo4j.jdbc.Connection;
import org.neo4j.jdbc.PreparedStatement;
import org.neo4j.jdbc.ResultSet;
public class Neo4jConnectionTest {
public static void main(String[] args) {
// Connect
Connection con = DriverManager.getConnection(
"jdbc:neo4j:bolt://localhost");
// Querying
String query = "MATCH (u:User)-[:FRIEND]-(f:User)
WHERE u.name = {1}
RETURN f.name, f.age";
try {
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1,"John");
ResultSet rs = con.execute();
while (rs.next()) {
System.out.println(
"Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
}
} catch (Exception e) { e.printStackTrace(); }
con.close();
}
}
I am unable to compile this as:
DriverManager cannot be resolved within the neo4j-jdbc-3.0,
Prepared stmt = con.prepareStatement(query); causes a type mismatch,
and con.execute() is undefined for type org.neo4j.jdbc.Connection
I'd greatly appreciate any advice and expertise on the matter, thanks.
By changing to:
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.0.4</version>
</dependency>
I was able to successfully connect to the Neo4j 3.0 server using an example from Neo4j's site:
public static void main(String[] args) {
Driver driver = GraphDatabase.driver(
"bolt://localhost", AuthTokens.basic( "neo4j", "neo4j" ) );
Session session = driver.session();
session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );
StatementResult result = session.run(
"MATCH (a:Person)
WHERE a.name = 'Arthur'
RETURN a.name AS name, a.title AS title");
while ( result.hasNext() ) {
Record record = result.next();
System.out.println( record.get( "title" ).asString() +
" " + record.get("name").asString() );
}
session.close();
driver.close();
}
I thought I'd share as this worked instantly with no hassle.
Neo4j Language Guides
DriverManager, Connection, PreparedStatement and ResultSet are all classes or interfaces from the java.sql package, which is part of the JDK. I guess the documentation assumes you'll use an IDE which will find the correct import for you.
It's the point of using the JDBC driver: you use the JDBC API, not a proprietary one (i.e. in a vendor package).
Update
There was a typo in the neo4j-jdbc readme, it should have read
ResultSet rs = stmt.execute();
instead of
ResultSet rs = con.execute();
otherwise the PreparedStatement has not use (and the code doesn't compile because there's no no-arg overload of Connection.execute()).
Update 2
The documented dependency was also wrong, as neo4j-jdbc does not contain any driver.
You should depend on:
either the all-in-one module, which gives you the opportunity to use the Bolt or HTTP protocols:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-driver</artifactId>
<version>3.0</version>
</dependency>
or the module for a specific protocol:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-bolt</artifactId>
<version>3.0</version>
</dependency>
<!-- or -->
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-http</artifactId>
<version>3.0</version>
</dependency>
Update 3
Both problems have now been fixed in the documentation of the project.

Getting error retrieving data from column family using cassandra-jdbc dreiver

when i am retrieving data from column family using Cssandra-JDBC driver. i got error
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.cassandra.thrift.Cassandra$Client.execute_cql3_query(Ljava/nio/ByteBuffer;Lorg/apache/cassandra/thrift/Compression;Lorg/apache/cassandra/thrift/ConsistencyLevel;)Lorg/apache/cassandra/thrift/CqlResult;
at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:447)
at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:472)
at org.apache.cassandra.cql.jdbc.CassandraStatement.doExecute(CassandraStatement.java:161)
at org.apache.cassandra.cql.jdbc.CassandraStatement.executeQuery(CassandraStatement.java:226)
at CassandraJDBCTest.main(CassandraJDBCTest.java:19)
Code is
public static void main (String args[]) throws SQLException{
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/TestExample");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Name,Age FROM Users WHERE keyname='001';");
rs.next();
System.out.println(rs.getString("Name"));
System.out.println(rs.getInt(2));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You have missing dependencies:
Exception in thread "main" java.lang.NoSuchMethodError
I have a feeling that the classpath is just not configured correctly (why the L's?):
Ljava/nio/ByteBuffer;
Lorg/apache/cassandra/thrift/Compression;
Lorg/apache/cassandra/thrift/ConsistencyLevel;
...
If you want to save yourself of dependency hell try using maven, the Datastax java driver has a maven central repo and you just need to include the dependency:
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>1.0.2</version>
</dependency>
EDIT
Sorry, didnt realise you are using JDBC. The cassandra jdbc driver has also got a maven repository:
<dependency>
<groupId>org.apache-extras.cassandra-jdbc</groupId>
<artifactId>cassandra-jdbc</artifactId>
<version>1.2.5</version>
</dependency>

Categories