Difference between Mysql-Connector- Java vs Spring-Jdbc - spring

As far as I know we use Mysql-connector jar for connecting java application to the database. I am following a spring tutorial and both the above mentioned things have been added via maven. What is the difference between both?

MySQL Connector is a driver that allows Java to talk to MySQL.
Spring JDBC is a library that makes it easier to write JDBC code. JdbcTemplate is particularly useful.
Before JdbcTemplate:
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int count;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
rs = statement.executeQuery("select count(*) from foo");
if(rs.next()) {
count = rs.getInt(0);
}
} catch (SQLException exp) {
throw new RuntimeException(exp);
} finally {
if(connection != null) {
try { connection.close(); } catch (SQLException exp) {}
}
if(statement != null) {
try { statement.close(); } catch (SQLException exp) {}
}
if(rs != null) {
try { rs.close(); } catch (SQLException exp) {}
}
}
After JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("select count(*) from foo", Integer.class);
See how one way sucks much less?

Related

how to convert blob data into byte array and get image from DB and send it to UI through rest api

#Override
public byte[] findByusernameAndtenantId(String username,int tenantId) throws SQLException {
Connection con=null;
Blob img ;
byte[] imgData = null ;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con=DriverManager.getConnection("jdbc:cassandra://169.46.155.77:9042/demo");
String query = "SELECT PHOTO FROM demo.IGNITE_USERS where USER_NAME=? and TENANT_ID=?";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next ())
{
img = result.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
result.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try{
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
return imgData ;
}
this is my implementation code .
#RequestMapping(value ="/Image",method = RequestMethod.POST, produces="image/jpg")
public ResponseEntity<byte[]> getImage(#RequestParam String username,#RequestParam int tenantId) throws SQLException
{
byte[] img=null;
img=authService.findByusernameAndtenantId(username,tenantId);
System.out.println("testing functionality");
return new ResponseEntity<byte[]>(img, HttpStatus.OK);
}
this is my controller code
when I run the spring boot program , and do a POST call in Postman client to get the image I am getting Class not found exception : org.apache.cassandra.cql.jdbc.Cassandra Driver.
Can you please help me how to return that image from cassandra DB stored as Blob ?

Cannot close Oracle connection from WebSphere datasource

I try to connect to Oracle database (check connection status). I'm using following code, which works fine.
public String getDatabaseStatus() {
Connection conn;
try {
conn = DriverManager.getConnection( "jdbc:oracle:thin:#192.168.0.70:1521:XE", "foo","bar");
conn.close();
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
However, when using Websphere datasource, after 10 (connection limit) refreshes page hangs. Code:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
conn = WSCallHelper.getNativeConnection(ds.getConnection());
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
I tried to close provided connection, but it gives me error:
J2CA0206W - A connection error occurred. To help determine the problem, enable the Diagnose Connection Usage option on the Connection Factory or Data Source. This is the multithreaded access detection option. Alternatively check that the Database or MessageProvider is available.
Any help will be appreciated.
You must close the connection that you received from the DataSource:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
java.sql.Connection connection = ds.getConnection();
try {
conn = WSCallHelper.getNativeConnection(connection);
} finally {
safeClose(connection);
}
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
private void safeClose(java.sql.Connection connection) {
try {
connection.close();
} catch (SQLException e) {
log.warn("Failed to close database connection", e);
}
}
If you're using Java 7 or better you can simplify it to:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
try (java.sql.Connection connection = ds.getConnection()) {
conn = WSCallHelper.getNativeConnection(connection);
}
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
If you fail to do this your connections will not be returned to the pool and you will run out of connections.

I get a nullpointerexception when connecting to oracle DataBase

Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
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 = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.

JDBC Update on Oracle failed to commit

I have JDBC Dao Object, and used PreparedStatements to do UPDATE a row at a table in my DB.
I have other methods such as SELECT and INSERT which are successful (insert-commit works).
But the update, just does not commit the changes (does not work at all). While the same UPDATE statement works from Oracle SQLServer directly.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StaffDAO {
private Connection conn;
public StaffDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Oracle Driver not found");
System.exit(0);
}
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#db01.xxxdev.com:1521:training",
"training", "training");
} catch (SQLException e) {
System.out.println("Driver manager failed");
}
}
public ResultSet getAllResultSet() {
String sql = "select * from ben_staff";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
return rs;
}
public Staff viewEmployee(String id) throws Exception {
Staff st = new Staff();
String sql = "SELECT * from BEN_STAFF where BEN_STAFF.id =\'" + id
+ "\'";
// String psql = "SELECT * FROM BEN_STAFF WHERE ID = ?";
Statement statement = null;
// PreparedStatement pstatement = null;
try {
statement = conn.createStatement();
// pstatement = conn.prepareStatement(psql);
// pstatement.setString(1, id);
} catch (SQLException e) {
System.out.println("Create Statement failed");
System.exit(1);
}
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
// rs = pstatement.executeQuery();
while (rs.next()) {
st.setId(rs.getString("ID"));
st.setLastName(rs.getString("LASTNAME"));
st.setFirstName(rs.getString("FIRSTNAME"));
st.setMi(rs.getString("MI"));
st.setAddress(rs.getString("ADDRESS"));
st.setCity(rs.getString("CITY"));
st.setState(rs.getString("STATE"));
st.setTelephone(rs.getString("TELEPHONE"));
st.setEmail(rs.getString("EMAIL"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return st;
}
public boolean insert(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "insert into ben_staff (id, lastname, firstname, mi, address, city, state, telephone, email)"
+ "values (?,?,?,?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(psql);
// pstmt.setString(1,st.getId());
// pstmt.setString(2, st.getLastName());
// pstmt.setString(3, st.getFirstName());
pstmt.setString(1, id);
pstmt.setString(2, last);
pstmt.setString(3, first);
pstmt.setString(4, mi);
pstmt.setString(5, address);
pstmt.setString(6, city);
pstmt.setString(7, state);
pstmt.setString(8, telephone);
pstmt.setString(9, email);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public boolean update(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "update ben_staff set lastname=?, firstname=?, mi=?, address=?, city=?, state=?,"
+ " telephone=?, email=? where id=?";
try {
pstmt = conn.prepareStatement(psql);
pstmt.setString(1, last);
pstmt.setString(2, first);
pstmt.setString(3, mi);
pstmt.setString(4, address);
pstmt.setString(5, city);
pstmt.setString(6, state);
pstmt.setString(7, telephone);
pstmt.setString(8, email);
pstmt.setString(9, id);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try{
conn.rollback();
} catch (SQLException exx){
System.out.println("Update Rollback Failed");
}
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What does pstmt.executeUpdate(); return? That would tell you how many rows are being updated. Something like
int numRows = pstmt.executeUpdate();
System.out.println( "Update modified " + numRows + " rows." );
My guess is that your update isn't actually modifying any rows. That would imply that the id being passed in was incorrect. Remember that string comparisons in SQL Server are case insensitive by default while they are case sensitive by default in Oracle.

Code Logic of when close the statement java

Well always teach me this way of open and close connections from database, then i search more and more because this is very important for the performance of my application.
Here is my Class connection
public class Connection {
jdbc:oracle:thin:#//xxx.xx.x.xxx:xxxx/xxxxx.xxxxxx.xxxxx.xxx;
protected static Connection cn = null;
protected Connection getCn() {
return cn;
}
public static void setCn(Connection cn) {
Connection.cn = cn;
}
public ResultSet select(String sql) throws Exception {
ResultSet rs = null;
Statement st = null;
try {
st = this.getCn().createStatement();
rs = st.executeQuery(sql);
} catch (java.sql.SQLException e) {
throw e;
}
return rs;
}
public void insert(String sql) throws Exception {
Statement st = null;
try {
st = this.getCn().createStatement();
st.executeUpdate(sql);
} catch (java.sql.SQLException e) {
throw e;
}
}
public Connection connect() throws Exception {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
setCn(DriverManager.getConnection(DBURL, "user", "password"));
} catch (java.sql.SQLException e) {
throw e;
}
return cn;
}
Well that was for my Connection Class, now here i have some others class that extends from my Connection class to bring me data from the DataBase.
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}
im using jsf and oracle, i think this snippet should be in my class Connection after the catch but generates me and error of the resulset is closed when i execute the method rs.next() and is logic because the statement must be close after the reading data of the resultSet, so how can i close the statement in my class Connection or in other place??? any suggestions? please help me
finally {
if (st != null) {
st.close();
}
}
A quick fix to the problem is:
finally {
try{ st.close(); }catch( Exception ex ) { /* do nothing*/ }
}
this prevents from throwing an error when something goes wrong with the statement in other places of the code ( st is null, st is closed etc.).
A more elegant solution might be creating a helper class with methods that close statements, resultsets etc. and hide exceptions that occur:
class DbCloser{
static void closeQuietly( Statement st ){
try{
st.close();
} catch( Exception ex ){
/* do nothing */
}
}
static void closeQuietly( ResultSet rs ){
try{
rs.close();
} catch( Exception ex ){
/* do nothing */
}
}
// .... etc.
}
and then use that helper class in finally blocks in code:
finally {
DbCloser.closeQuietly( st );
}
There is ready-made DbUtils package from Appache Commons that has already implemented such helper methods, just download this library and place it in the class-path, see this links for details:
http://commons.apache.org/proper/commons-dbutils/
http://commons.apache.org/proper/commons-dbutils/apidocs/index.html
And finally I would suggest to place close methods only in finnaly blocks:
try {
......
rs = this.select(sql);
.......
...........
// Do not close the statement here ......
// rs.close(); //here is my dude because when may i can put the statement.close() line?
} catch (Exception e) {
throw e;
} finally {
// ..... always close it here !!!
DbUtils.closeQuietly( st );
.........
}
i use this one
finally {
try{
if(st!=null){
st.close();
st=null;
}
}catch( Exception ex )
{
/* you can log this*/
}
}
Finally, I solved it like this:
public String checkMethod() throws Exception {
ResultSet rs;
String sql = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
this.connect();
rs = this.select(sql);
while (rs.next()) {
//some data collect
}
rs.close();
rs.getStatement().close(); 'This works for me =)
} catch (Exception e) {
throw e;
} finally {
this.cerrar();
}
return "success";
}

Resources