I'm trying to store an sql request into an object so I can load/save information from this object.
Unfortunalty it seems I miss something... But I dunno what :D
When I execute my code I get an error saying :
"java.lang.Integer cannot be cast to [B"
(I catch this message in ClassCastException)
Here is what I do :
public static CatalogueClients chargementClient() throws ClassNotFoundException, IOException, SQLException {
// TODO Auto-generated method stub
Connection dbConnection = null;
Statement statement = null;
CatalogueClients maliste = new CatalogueClients();
try {
dbConnection = OpenConnexion.getDBConnection();
statement = dbConnection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM client");
while (result.next()) {
byte[] st = (byte[]) result.getObject(1);
ByteArrayInputStream bais = new ByteArrayInputStream(st);
ObjectInputStream ois = new ObjectInputStream(bais);
maliste = (CatalogueClients) ois.readObject();
ois.close();
bais.close();
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassCastException cce){
System.out.println(cce.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
return maliste;
}
Here is what CatalogueClients look like :
public class CatalogueClients extends ArrayList<Client> {
private static CatalogueClients instance;
private static final long serialVersionUID = 1L;
public String Afficher() {
return (Input.returnOption("Mes clients: "));
}
public static CatalogueClients getInstance() throws SQLException {
if (instance == null) {
instance = Serialization.chargementClient();
}
return instance;
}
Can you guys please help ?
Thanks
Verify datatype of first column in table (which is returned by query) and modify code accordingly. As per error message mentioned, it is clear that you are receiving Integer value as value of first column.
List<Client> clients = new ArrayList<>();
Client client=null;
try {
dbConnection = OpenConnexion.getDBConnection();
statement = dbConnection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM client");
while (result.next()) {
client = new Client();
client.setId(result.getInt(1));
//Map other properties likewise here
clients.add(client);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassCastException cce){
System.out.println(cce.getMessage());
} finally {
maliste ==clients; // set list here
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
Related
I am currently facing connection leak problem in my code (Java , Struts). I have closed all the result sets, prepared statements, callable statements and the connection in the finally blocks of all the methods in my dao. still I face the issue.Additional information is , I am using StructDescriptor.createDescriptor for creating oracle objects. Will it cause any connection leaks? Please advise.
Code below
public boolean updatedDetails(Distribution distribution, String appCode, Connection dbConnection) {
boolean savedFlag = true;
CallableStatement updateStoredProc = null;
PreparedStatement pstmt1 = null;
try {
logger.debug("In DistributionDAO.updatedDistributionDetails");
//PreparedStatement pstmt1 = null;
ARRAY liArray = null;
ARRAY conArray = null;
ARRAY payArray = null;
ArrayDescriptor licenseeArrDesc = ArrayDescriptor.createDescriptor(LICENSEE_TAB, dbConnection);
ArrayDescriptor contractArrDesc = ArrayDescriptor.createDescriptor(DISTRIBUTION_CONTRACT_TAB, dbConnection);
ArrayDescriptor paymentArrDesc = ArrayDescriptor.createDescriptor(DISTRIBUTION_PAYMENT_TAB, dbConnection);
licenseeArray = new ARRAY(licenseeArrDesc, dbConnection, licenseeEleList.toArray());
contractArray = new ARRAY(contractArrDesc, dbConnection, contractEleList.toArray());
paymentArray = new ARRAY(paymentArrDesc, dbConnection, paymentEleList.toArray());
updateStoredProc = dbConnection.prepareCall("{CALL DIS_UPDATE_PROC(?,?,to_clob(?),?,?,?,?)}");
updateStoredProc.setLong(1, distribution.getDistributionId());
updateStoredProc.setString(2, distribution.getId());
updateStoredProc.setString(3, distribution.getNotes());
updateStoredProc.setString(4, distribution.getNotesUpdateFlag());
updateStoredProc.setArray(5, liArray);
updateStoredProc.setArray(6, conArray);
updateStoredProc.setArray(7, payArray);
String sql1="Update STORY set LAST_UPDATE_DATE_TIME= sysdate WHERE STORY_ID = ? ";
pstmt1=dbConnection.prepareStatement(sql1);
pstmt1.setLong(1,distribution.getStoryId());
pstmt1.execute();
List<Object> removedEleList = new ArrayList<Object>();
removedEleList.add(createDeleteElementObject(removedEle, dbConnection));
catch (SQLException sqle) {
savedFlag = false;
} catch (Exception e) {
savedFlag = false;
} finally {
try {
updateStoredProc.close();
updateStoredProc = null;
pstmt1.close();
pstmt1 = null;
dbConnection.close();
} catch (SQLException e) {
}
}
return savedFlag;
}
// Method createDeleteElementObject
private Object createDeleteElementObject(String removedEle,
Connection connection) {
StructDescriptor structDesc;
STRUCT structObj = null;
try {
structDesc = StructDescriptor.createDescriptor(DISTRIBUTION_REMOVED_ELEMENT_OBJ, connection);
if(removedEle != null) {
String[] tmpArr = removedEle.split("\\|");
if(tmpArr.length == 2) {
Object[] obj = new Object[2];
String eleType = tmpArr[0];
long eleId = Integer.parseInt(tmpArr[1]);
obj[0] = eleType.toUpperCase();
obj[1] = eleId;
structObj = new STRUCT(structDesc, connection, obj);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
} catch (NumberFormatException e) {
} catch (SQLException e) {
}
return structObj;
}
Some hints on your code:
You pass a Connection variable into your call but close it inside your call - is the caller aware of that fact? It would be cleaner to get the connection inside your code or return it unclosed (calling method is responsible)
Exceptions are meant to be caught, not ignored - you don't log your exception - you'll never know what happens. I bet a simple e.printStackTrace() in your catch blocks will reveal helpful information.
Use try-with-resource (see this post)
//Resources declared in try-with-resource will be closed automatically.
try(Connection con = getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
//Process Statement...
} catch(SQLException e) {
e.printStackTrace();
}
At the very least put every close inside single try-catch:
} finally {
try {
if(updateStoredProc != null) {
updateStoredProc.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt1!= null) {
pstmt1.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
i have an function connexion to a database
and i have a code that i have a select and display elements in a combobox
so i want pass on class connexion.java the combobox selectedItem becaue it contains the all of databases that i have
so i want tha classe connexion be dynamic so pass the element selected on this class
i don"t know how can i do that please help me
public class Connexion {
private static Connection conn;
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
public static Connection getconx()
{
return conn;
}
}
Use this class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.jdbc.rowset.CachedRowSet;
public class SQLConnection {
private static Connection con = null;
private static BasicDataSource dataSource;
//we can enable and disable connection pool here
//true means connection pool enabled,false means disabled
private static boolean useConnectionPool = true;
private static int count=0;
private SQLConnection() {
/*
Properties properties = new Properties();
properties.load(new FileInputStream(""));
maxActive = properties.get("maxActive");
*/
}
public static String url = "jdbc:mysql://localhost:3306/schemaname";
public static String password = "moibesoft";
public static String userName = "root";
public static String driverClass = "com.mysql.jdbc.Driver";
public static int maxActive = 20;
public static int maxIdle = 10;
private static final String DB_URL = "driver.classs.name";
private static final String DB_USERNAME = "database.username";
static {
/*Properties properties = new Properties();
try {
properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties"));
//properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF"));
//properties.load(new FileInputStream("D:\\DatabaseConnection.properties"));
url = properties.getProperty(DB_URL);
System.out.println(url);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(maxIdle);
dataSource.setMaxIdle(maxIdle);
}
//public static Connection getConnection(String opendFrom) throws SQLException,
public static Connection getConnection(String openedFrom) {
count++;
System.out.println("nos of connection opened till now="+count);
System.out.println("Connection opended from "+openedFrom);
// System.out.println("Connection Opended ");
try {
if (useConnectionPool) {
con = dataSource.getConnection();
System.out.println(dataSource.getMinEvictableIdleTimeMillis());
//dataSource.setMaxWait(15000);
System.out.println(dataSource.getMaxWait());
System.out.println(count );
} else {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, userName, password);
}
}
//System.out.println("Connection : " + con.toString());
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void closeConnection(Connection con, String closedFrom)
{
//System.out.println("Connection closed from: " + con.toString());
// System.out.println("Connection closed from: " + closedFrom);
//log.info("Connection closed from: " + closedFrom);
if(con != null){
count--;
System.out.println("Connection count value after closing="+count);
System.out.println("Connection closed from: " + closedFrom);
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
public static void closeStatement(Statement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closePreparedStatement(PreparedStatement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeResultSet(ResultSet rs, String closedFrom)
{
if(rs != null){
System.out.println("ResultSet closed from: " + closedFrom);
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
/*public static ResultSet executeQuery(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
CachedRowSet crset = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
crset = new CachedRowSet();
crset.populate(rs);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return crset;
}
public static int executeUpdate(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int rows = -1;
try {
con = getConnection();
stmt = con.createStatement();
rows = stmt.executeUpdate(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rows;
}
public static boolean execute(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean rowsreturned = false;
try {
con = getConnection();
stmt = con.createStatement();
rowsreturned = stmt.execute(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rowsreturned;
}*/
/*
* public static void closeConnection(Connection con) { try { con.close();
* con=null; } catch (SQLException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
A JComboBox accepts any kind of object, so you can simply do something like this.
Connection con = new Connection();
JComboBox box = getBox();
box.addItem(con);
And to retreive the value:
JComboBox box = getBox();
Connection con = (Connection)box.getSelectedItem();
However in your Connection class you must override the toString() function, because this is used to display the box.
class Connection
{
public String toString()
{
return "BoxItemDisplayvalue"; <--- here you must put something meaningfull which is displayed in the box.
}
}
So you can instantiate a connection representing the connection that you want, and when the user selects an item from the combobox, you will have the connection it represents.
For what i understand, you have 2 classes..
One the gui where you have a comboBox with the schema name where u want to get connected.
So you have to have a EventListener to "listen" when the submit button is pressed.
For example:
Connection con = null;
JButton submitButton = new JButton("Confirm db");
submitButton.addActionListener(new MyConnectionListener());
..
//Could be inner class
class MyConnectionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt){
if(cmb.getSelectedItem() != null){
con = Connection.getConx(cmb.getSelectedItem().toString());
}
}
}
And in your Connexion class
public class Connexion {
public static Connection getconx(String schema)
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
return conn;
}
}
When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
It's been a while since I have done any Java programming. And I find my self a bit stuck.
My problem is that I have a pooled db connection in tomcat. That is working nicely. But there is a lot of boiler plate required.
public void init() {
Connection conn = null;
ResultSet rst = null;
Statement stmt = null;
try {
//SETUP
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env/jdbc");
OracleDataSource ds = (OracleDataSource) envContext.lookup("tclsms");
if (envContext == null) throw new Exception("Error: No Context");
if (ds == null) throw new Exception("Error: No DataSource");
if (ds != null) conn = ds.getConnection();
if (conn == null) throw new Exception("Error: No Connection")
message = "Got Connection " + conn.toString() + ", ";
//BODY
stmt = conn.createStatement();
rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
if (rst.next()) message = rst.getString(1);
//TEAR DOWN
rst.close();
rst = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (Exception e) {
e.printStackTrace();
//TODO proper error handling
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rst != null) {
try {
rst.close();
} catch (SQLException e) {;}
rst = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {;}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {;}
conn = null;
}
} //END FINALLY
} //END INIT
So I want to do the equivalent of passing a method into init that will run in the body of the function. I know I can't do this in Java. But I'm sure there must be a nice way to do this. Or at least a best practice for this sort of thing.
Any help much appreciated.
abstract class UseDBConnectionTask extends Runnable {
private Connection conn;
public UseDBConnectionTask(){
setUp();
}
// should probably refine this to specific exceptions
public abstract void process() throws Exception;
public void run(){
try{
process()
// this should catch specific exceptions
} catch (Exception e){
// handle
} finally {
tearDown();
}
}
Connection getConnection(){
return conn;
}
public void setUp(){
// SETUP here
// set the conn field
}
public void tearDown(){
// TEAR DOWN here
}
}
use like:
UseDBConnectionTask dbTransaction = new UseDBConnectionTask(){
public void process(){
// do processing
// use conn via getConnection()
// eg
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
String message = null;
if (rst.next()) message = rst.getString(1);
}
}
new Thread(dbTransaction).start();
The advantage of extending Runnable is that you can then pass this instance into a thread pool or similar.
Just have to be careful of threading issues. It also assumes that the tear down is always the same.
You should prefer delegation to inheritance. The above can/will work but isn't well thought out.
Implementing Runnable on the primary class exposes it for abuse because the 'run()' method is public.
A second improvement is to use to delegate your activity to an interface (and this CAN be passed around like a function pointer whereas extending the class cannot). In addition, it makes it Spring friendly
This allows the action implementer to decide if they want multi-threaded behavior or not. You can inject composites, caching delegates, etc and the primary class is none-the-wiser. This conforms with good design practice of separation of concerns
public class MyClass {
private Action action;
public MyClass (Action action) {
this.action = action;
}
public void connection() {
try{
action.perform()
} catch (Exception e){
// handle
} finally {
tearDown();
}
}
Connection getConnection(){
return conn;
}
private void setUp(){
// SETUP here
// set the conn field
}
private void tearDown(){
// TEAR DOWN here
}
}
interface IDbAction {
public DbActionResult runAction(Connection conn);
}
class DbActionResult {
Statement statement;
ResultSet resultSet;
public DbActionResult(Statement statement, ResultSet resultSet){
this.statement = statement;
this.resultSet = resultSet;
}
public void getStatement(){ return this.statement; }
public void getResultSet(){ return this.resultSet; }
}
public void runAgainstDB(IDbAction action) {
Connection conn = null;
ResultSet rst = null;
Statement stmt = null;
try {
//SETUP
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env/jdbc");
OracleDataSource ds = (OracleDataSource) envContext.lookup("tclsms");
if (envContext == null) throw new Exception("Error: No Context");
if (ds == null) throw new Exception("Error: No DataSource");
if (ds != null) conn = ds.getConnection();
if (conn == null) throw new Exception("Error: No Connection")
message = "Got Connection " + conn.toString() + ", ";
//BODY
DbActionResult actionResult = action.runAction(conn);
//TEAR DOWN
if((rst = actionResult.getResultSet()) != null){
rst.close();
rst = null;
}
if((stmt = actionResult.getStatement()) != null){
stmt.close();
stmt = null;
}
actionResult = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (Exception e) {
e.printStackTrace();
//TODO proper error handling
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rst != null) {
try {
rst.close();
} catch (SQLException e) {;}
rst = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {;}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {;}
conn = null;
}
} //END FINALLY
} //END
Use like:
IDbAction action = new IDbAction(){
public DbActionResult prcoessAction(Connection conn){
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
if (rst.next()) message = rst.getString(1);
return new DbActionResult(stmt, rst);
}
}
runAgainstDB(action);
private void Todo(Context initContext, Context envContext, OracleDataSource ds){
if (envContext == null) throw new Exception("Error: No Context");
if (ds == null) throw new Exception("Error: No DataSource");
if (ds != null) conn = ds.getConnection();
if (conn == null) throw new Exception("Error: No Connection")
message = "Got Connection " + conn.toString() + ", ";
//BODY
stmt = conn.createStatement();
rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
if (rst.next()) message = rst.getString(1);
//TEAR DOWN
rst.close();
rst = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (Exception e) {
e.printStackTrace();
//TODO proper error handling
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rst != null) {
try {
rst.close();
} catch (SQLException e) {;}
rst = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {;}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {;}
conn = null;
}
} //END FINALLY
}
Then call it from your Init like this this. Todo(initContext,envContext , ds)
It seems a very basic question but I couldn't find any resolution for it.
I have following code with me:
package com.test.db.util;
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 JDBCConnect
{
private Connection conn = null;
private final String uname = "root";
private final String passwd = "test#123";
private String url = "jdbc:mysql://127.0.0.1:3306/TrainDB";
private final String className = "com.mysql.jdbc.Driver";
public void initConnection()
{
try
{
if(this.conn == null || this.conn.isClosed())
{
try
{
Class.forName (className).newInstance ();
this.conn = DriverManager.getConnection(url, uname, passwd);
System.out.println("database connection established.");
}
catch(SQLException sqe)
{
sqe.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
//return this.conn;
}
public void disconnect()
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
public void insertData(String sql)
{
PreparedStatement s;
try
{
if(conn == null || conn.isClosed())
{
initConnection();
}
s = conn.prepareStatement(sql);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
}
catch (SQLException e)
{
e.printStackTrace();
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception se) { /* ignore close errors */ }
}
}
}
public ResultSet query(String sql)
{
Statement s = null;
try
{
if(this.conn == null || this.conn.isClosed())
{
initConnection();
}
s = conn.createStatement();
s.executeQuery(sql);
ResultSet rs = s.getResultSet();
System.out.println("lets see " + rs.getFetchSize());
return rs;
}
catch(SQLException sq)
{
System.out.println("Error in query");
return null;
}
finally
{
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I am using JDBCConnect in a different class:
import java.sql.ResultSet;
import java.sql.SQLException;
public class traininfo
{
public static void main(String[] args)
{
JDBCConnect jdbcConn = new JDBCConnect();
String sql = "SELECT id FROM testtable";
ResultSet rs = jdbcConn.query(sql);
try {
System.out.println(rs.getFetchSize());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rs != null)
{
try
{
while(rs.next())
{
System.out.println(rs.getString("id"));
}
rs.close();
}
catch(SQLException sqe)
{
}
}
jdbcConn.disconnect();
}
}
I am not using concurrent calls for insertion and reads. If I use the same query in mysql-workbench (client), I am getting proper results but using the mentioned code, I am getting
database connection established.
lets see 0
0
Database connection terminated
Please suggest me what I am missing?
Most probably it's because you're closing Statement before you are using it's ResultSet. It's strange that it doesn't throw an exception, but this is not correct anyway.
As per Statement.close method JavaDoc:
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
I suggest to use some kind of callback to retrieve results from ResultSet before it's closed e.g.:
public <T> T query(String sql, IResultSetHandler<T> resultSetHandler ) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
final ResultSet rs = connection.executeQuery(sql);
final T result = resultSetHandler.handle(rs);
return result;
} finally {
if(statement != null) {
statement.close();
}
}
}
public interface IResultSetHandler<T> {
T handle(ResultSet rs);
}
public static void main(String[] args) {
JDBCConnect jdbcConn = new JDBCConnect();
List<String> ids = jdbcConn.query(sql, new IResultSetHandler<List<String>>() {
public List<String> handle(ResultSet rs) {
List<String> ids = new ArrayList<String>();
while(rs.next()) {
ids.add(rs.getString("id"));
}
return ids;
}
});
}
Or to use commons apache dbutils library which does exactly the same.
ResultSet.getFetchSize() lets you know the maximum number of rows that the connection will fetch at once. You can set it with ResultSet.setFetchSize(int). See also the official documentation. It does not tell you how many rows in total you will get. If the fetch size is left to zero, JDBC decides on its own.
Other than that, refer to Yura's answer which addresses the core of your problem.
Could it be because you never call InsertRows, as it never shows that 'X rows were inserted'