Obtain an OracleDataSource in SpringBoot 2 - java

Is it possible to retrieve a OracleDataSource from the default SpringBoot 2 Hikari connection pool using a NamedParameterJdbcTemplate object?
Using Java 8, Oracle 11g (ojdbc6-11.2.0.1.jar) and gradle
This is what i've tried.
#Repository
public class MyClass{
#Autowired
NamedParameterJdbcTemplate jdbcTemplate;
public void myMethod(){
try{
//OracleDataSource ods = new OracleDataSource(); // This works but is obviously not Spring
OracleDataSource ods = (OracleDataSource) jdbcTemplate.getJdbcTemplate().getDataSource(); // This fails
ods.setURL(url);
ods.setUser(user);
ods.setPassword(pass);
...
catch(Exception e){
System.out.println("In Exception");
e.printStackTrace();
}
}
}
Application.properties:
spring.datasource.url=jdbc:oracle:thin:#//${ORA_HOST}:${ORA_PORT}/${ORA_SID}
spring.datasource.username=${USER}
spring.datasource.password=${PASS}
Error message:
In Exception
java.lang.ClassCastException: com.zaxxer.hikari.HikariDataSource cannot be cast to oracle.jdbc.pool.OracleDataSource

I don't think this is possible (or neccessary). The easiest way is to unwrap() a connection object, which has already connected to the dB:
Connection conn = this.jdbcTemplate.getJdbcTemplate().getDataSource().getConnection().unwrap(OracleConnection.class);

Just a query like, how are you able to get OracleConnection.class, because in my case I get squiggly line underneath OracleConnection.class and there are no packages available to import.

Related

java.sql.SQLException: No suitable driver found for jdbc://localhost:3306/twitch

I was trying to connect to MySQL "twitch" database using java with this code below:
import java.sql.*;
public class App {
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc://localhost:3306/twitch";
String username = "root";
String pass = "nfreal-yt10";
Connection con=DriverManager.getConnection(url,username,pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select distinct creator_id from twitch.information where creator_id > 40;");
while (rs.next()) {
System.out.println(rs.getString(1));
}
con.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
when I executed the code my console throws (Full error):
Loading class `com.mysql.jdbc.Driver'.
This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.
java.sql.SQLException: No suitable driver found for jdbc://localhost:3306/twitch
I have added MySQL connector on my directory folder and all stuff which required to be added, yet the error still occurred, why?
When you communicate with your database (located at /localhost:3306/twitch), you must precise the protocol used (eg. your browser use http or https protocol followed with the adress).
JDBC is a driver that can interface with MySQL, but can't directly access to your database. Hence your URL should be:
String url = "jdbc:mysql://localhost:3306/twitch";
EDIT : Class.forName("com.mysql.cj.jdbc.Driver"); is no more needed in general. Details here.

How to connect to postgres and execute query using r2dbc

I'm trying to write a simple function which will connect to postgres and execute a select statement.
PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.database("MyDB")
.username("username")
.password("password").build());
DatabaseClient client = DatabaseClient.create(connectionFactory);
Flux<Map<String, Object>> result = client.execute("select * from table").fetch().all();
result.map(s -> {
System.out.println(s);
return null;
});
The above piece of code isn't printing anything. There is no error as well. I can connect to DB using the same credentials. What is missing in the code to stream data from DB?
Create the configuration class which is similar to the below code to connect to the PostgreSQL database
#Configuration
#EnableR2dbcRepositories
public class DatabaseConfig extends AbstractR2dbcConfiguration {
#Override
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get("r2dbc:postgresql://localhost:5432/DATABASE_NAME");
}
}

getting Cannot create JDBC driver of class '' for connect URL 'jdbc:mysql://127.0.0.1:3306/config in Netbeans'

I've searched through similar questions and didn't find a solution that worked for me. I'm running following in Netbeans > servlet:
public Connection getConnection()
{
Connection result = null;
BasicDataSource dataSource = getDataSource();
try {
result = dataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Throwable e)
{
e.printStackTrace();
}
return result;
}
It works fine when executed in a Java project. Then I added this project's jar as a library to a servlet project in Netbeans - it throws exception:
"java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'jdbc:mysql://127.0.0.1:3306/config'"
It looks like this "class ''" thing should point to a class name but where do I get it?
fixed that. had to put drivers into glassfish/lib directory

TestContainers Oracle TimeoutException

I tried to use testcontainers library for integration tests with Oracle. Here is is the simple test:
public class SimpleTest {
#Rule
public OracleContainer oracle = new OracleContainer();
#Test
public void simpleTest() throws SQLException {
HikariDataSource ds = buildHikariDataSource();
Statement statement = ds.getConnection().createStatement();
statement.execute("SELECT 1 FROM dual");
ResultSet resultSet = statement.getResultSet();
resultSet.next();
int resultSetInt = resultSet.getInt(1);
assertEquals("A basic SELECT query succeeds", 1, resultSetInt);
}
private HikariDataSource buildHikariDataSource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(oracle.getJdbcUrl());
hikariConfig.setUsername(oracle.getUsername());
hikariConfig.setPassword(oracle.getPassword());
return new HikariDataSource(hikariConfig);
}
}
But it fails with TimeoutException:
Caused by: org.testcontainers.containers.ContainerLaunchException: Could not create/start container
at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:256)
at org.testcontainers.containers.GenericContainer.lambda$start$0(GenericContainer.java:184)
at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:76)
... 18 more
Caused by: org.rnorth.ducttape.TimeoutException: org.rnorth.ducttape.TimeoutException: java.util.concurrent.TimeoutException
at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:53)
at org.testcontainers.containers.JdbcDatabaseContainer.waitUntilContainerStarted(JdbcDatabaseContainer.java:81)
at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:235)
... 20 more
My Docker installation is suitable with testcontainers-oracle-xe and os is macOS Sierra 10.12.6.
How can this problem be resolved?
P.S. Full console output
All in all I created an issue in testcontainers-java-module-oracle-xe repository.
The solution was to change location to US and language to English in System Preferences.
The answer from testcontainers engineer:
My colleague have faced the same problem. We have debugged and
understood that problem with oracle TNS (ORA-12514). In order to
resolve it, there is a need to change language to English and location
to US.

JDBC JAVA No suitable driver found for jdbc:mysql://localhost:3306/voting

Hello im trying to connect to a mysql database using JDBC my code is below.I get an error as such No suitable driver found.Searching around I found that the usual error is syntax or missing the jar file from the class path.I tried both of these solutions and dont know what to do next it wont connect.Also to manage the databases I have WAMP and mySQL workbench installed not sure if its related.
package test.jdbc;
import java.sql.*;
public class jdbctester {
public static void main(String[] args)
{
try
{
Connection myconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/voting","root","Vanquish123");
Statement myStmt=myconn.createStatement();
ResultSet myRs=myStmt.executeQuery("select * from electoral");
/*
while(myRs.next())
{
System.out.println(myRs.getString("state")+","+myRs.getString("perDem"));
}
*/
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
Try this:
Class.forName("fully qualified driver class name");
Java Class.forName, JDBC connection loading driver
this post states that you should not need it but it will not hurt you to try.
you have to add "com.mysql.jdbc_5.1.5.jar" in to your project build path... go to project property>build Path> library> add external jar and add jar file.
Connection conn = null;
try {
// Register JDBC driver
Class.forName(DRIVER).newInstance();
// Open a connection
conn = DriverManager.getConnection(Local_URL + , USERNAME, PASSWORD);
System.out.println("Connected Database Successfully...\n\n");
} catch (Exception se) {
throw new AppException("Failed to create Local Database connection", se);
}
return conn;

Categories

Resources