Hi I'm getting nullpointerexception at rs.next() or rs.getString(1)
it is really weird that sometimes rs.next() works fine and it throws nullpointerexception at rs.getString("PRODUCTCODE"),sometimes it throws npe at rs.getString("PRODDATE")
i dont understand why rs.getString() thows npe while rs.next() works fine
Here is my code
{
ResultSet rs = null;
String query = "";
BarcodeBean bi = null;
try {
query = "SELECT * FROM TABLE(GET_BARCODEINFO('"barcode.trim()"'))";
statement = connection.createStatement();
Logger.getInstance().getLogger().logInfo(query);
rs = statement.executeQuery(query);
bi = new BarcodeBean();
if (rs == null){
if(rs.next()){
bi.setUrunKodu(rs.getString("PRODUCTCODE"));
bi.setImalatMakineKodu(rs.getString("PRODMACHINECODE"));
bi.setOperatorSicilNo(rs.getString("OPERATORID"));
bi.setImalatTarihi(rs.getString("PRODDATE"));
bi.setImalatVardiyasi(rs.getString("PRODSHIFT"));
bi.setSeriNumarasi(rs.getString("SERIALNUMBER"));
bi.setSirtTarihi(rs.getString("SIRTTARIHI"));
}
}
} catch (SQLException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseUtility.close(rs);
DatabaseUtility.close(statement);
}
}
probably you want:
if (rs != null) {
if (rs.next()) {
or even better:
if (rs != null && rs.next()) {
Your test is simply wrong.
Statement#executeQuery() never returns null. The whole nullcheck is superfluous. The normal idiom is the following:
public Entity find(Long id) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Entity entity = null;
try {
connection = database.getConnection();
preparedStatement = connection.prepareStatement(SQL_FIND);
preparedStatement.setLong(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
// ...
}
} finally {
close(connection, preparedStatement, resultSet); // In reversed order.
}
return entity;
}
Your actual problem lies somewhere else. This is clearly a misinterpretation of the stacktrace. To nail it correctly down, you need to lookup the line number of the first line in the stacktrace and point us the exact code at this line number.
From Statement javadocs:
public ResultSet executeQuery(String sql) throws SQLException
Returns: a ResultSet
object that contains the data produced
by the given query; never null
So, you don't need to verify whether rs == null.
The standard way to proceed resultset rows is:
while (rs.next ()) {
doSmth (rs);
}
You made a wrong notation in if condition,
So change it as,
if(rs!=null){
......
.......}
Related
I'm tying to get an image from MySQL database and show in a JLabel, but when I execute the query and try to get the bytes from the ResultSet it returns an empty array.
I tested the connection, and it is working, tested the query and its also working.
try {
conn = getConnection();
pst = conn.prepareStatement("select * from imagem where serial_imagem = 123658");
rs = pst.executeQuery()
if (rs.next()) {
image = rs.getBytes("img_imagem");
}
}catch (Exception e) {
e.printStackTrace();
}
The code does not close and thus leaks resources. The somewhat ugly Try-With-Resources syntax ensures closing connection, statement and result set, even on returning/exception.
One could make explicit with Optional whether the image was found in the table or not.
Optional.of also guarantees that the field in the database must not contain an SQL NULL value.
Optional<byte[]> loadImageFromDatabase(String imageM) throws SQLException {
String sql = "select img_imagem from imagem where serial_imagem = ?";
try (Connection conn = getConnection();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, imageM);
try (ResultSet rs = pst.executeQuery()) {
if (rs.next()) {
return Optional.of(rs.getBytes(1)); // ofNullable
} else {
return Optional.empty();
}
}
}
}
Usage:
try {
Optional<byte[]> img = loadImageFromDatabase(jtextField1.getText().trim());
img.ifPresent(image -> {
...
});
} catch (SQLException e) {
There is still to remark that I personally do not often use ResultSet.getBytes, but rather getInputStream. Depends on the image size and creation code.
I am trying to execute a query that returns a student whose name and last name concatenated equal the search key parameter.
For that I am doing this in my class that manages anything related to the database for my Student class.
When the query is executed I am getting the error that follows:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
What's wrong? I have checked that's the correct way to use concat.
name and lastName are VARCHAR in the mysql database.
public static Student findStudent(String key) {
if (key == null) return null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
String selectSQL = "select * from project.students where concat(name, lastName) = ? ;";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, key);
Student student = null;
rs = preparedStatement.executeQuery(selectSQL);
if (rs.next()) {
StudentDB.setStudentAttributes(student, rs);
}
return student;
} catch(SQLException e) {
e.printStackTrace();
} finally {
close();
try {
if (preparedStatement != null) preparedStatement.close();
if (rs != null) rs.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
return null;
}
Your problem is that you prepare the statement with
preparedStatement = dbConnection.prepareStatement(selectSQL);
which is correct, but then when you try to execute the PreparedStatement you supply the selectSQL string again:
rs = preparedStatement.executeQuery(selectSQL);
That is incorrect. You've already prepared the statement, so when the time comes to execute it you just do
rs = preparedStatement.executeQuery();
Trying to use prepareStatement on a query from an XML file:
<sql><![CDATA[
select MY_COLUMN from MY_TABLE where OTHER_COLUMN = ?
]]>
</sql>
But I get this exception:
com.ibm.db2.jcc.am.SqlException: [jcc][t4][10234][10927][3.59.81] SQL passed with no tokens. ERRORCODE=-4462, SQLSTATE=null
at com.ibm.db2.jcc.am.dd.a(dd.java:660)
at com.ibm.db2.jcc.am.dd.a(dd.java:60)
at com.ibm.db2.jcc.am.dd.a(dd.java:120)
at com.ibm.db2.jcc.am.jb.v(jb.java:7334)
at com.ibm.db2.jcc.am.jb.a(jb.java:2124)
at com.ibm.db2.jcc.am.jb.prepareStatement(jb.java:754)
I read that this is because the SQL is not in a single line. Is that the cause?
I also read that in IBM Portal, you have to change db2_zos.DbDriverType from 2 to 4. But I think it's irrelevant to me as I don't use IBM Portal.
Nothing else useful turned up from Google. I would love to know the real cause of the error, and to find an easier fix than forcing all SQL to single line.
Code:
ArrayList arrList = new ArrayList();
String sSQL = queryManager.getSQL("QRY001");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection(); //a connection pool wrapper for java.sql.DriverManager.getConnection(...)
ps = conn.prepareStatement(sSQL); // **** EXCEPTION OCCURS HERE
ps.setInt(1, Integer.parseInt(otherColumn));
rs = ps.executeQuery();
while (rs.next())
{
arrList.add(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
throw new OEException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
releaseConnection(conn);
} catch (Exception e) {
throw new CustomException(e);
}
}
return arrList;
Because the SQL execution has comments;
Please refer to the official documentation
https://www.ibm.com/support/pages/apar/PH14323
Also try writing it like this
<sql>
select MY_COLUMN from MY_TABLE where OTHER_COLUMN = ?
</sql>
I have the following method which uses JDBC to get data from the DB:
public List<QueryHolder> getData(String Name) throws SQLException {
OracleDataSource ds;
ds = new OracleDataSource();
String url="jdbc:oracle:thin:#192.***.*.**:1521/dbg";
ds.setURL(url);
Connection conn = null;
conn=ds.getConnection("name","password");
SQL_Str = "SELECT ASM4EVLENMEEHLIYETBELGESI.DAMATSOYAD,ASM4EVLENMEEHLIYETBELGESI.DAMATBABAADI,ASM4EVLENMEEHLIYETBELGESI.DAMATANNEADI FROM ASM4EVLENMEEHLIYETBELGESI where DAMATSOYAD like ('%"
+ Name + "%')";
Statement ps = conn.createStatement();
if (ps == null)
throw new SQLException("Can't get data source");
rs = ps.executeQuery(SQL_Str);
ps.close();
if (con != null) {
con.close();
}
if (rs == null)
throw new SQLException("Can't get data source");
List<QueryHolder> list = new ArrayList<QueryHolder>();
while (rs.next()) { // <-- This is line 89.
QueryHolder que = new QueryHolder();
que.setSoyad(rs.getString("DAMATSOYAD"));
que.setBabaadi(rs.getString("DAMATANNEADI"));
que.setAnneadi(rs.getString("DAMATBABAADI"));
list.add(que);
}
return list;
}
However, when I run this method, it throws the following exception:
java.sql.SQLException: Closed statement: next
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:147)
oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:187)
Que.Query.getData(Query.java:89)
...
How is this caused and how can I solve it?
Correct closing order :
The following procedures should be done (in order)
ResultSet
PreparedStatement
Connection.
Edited code
Statement ps = conn.createStatement();
...
rs = ps.executeQuery(SQL_Str);
...
while (rs.next()) { // <-- This is line 89.
...
}
ps.close();
con.close();
return list;
It is a good practice to keep you ps.close(); or other closing statements in the finally block. Instead of handling Exception on the method label use try and catch instead.
the problem in your case is you closed the Statement before and trying to iterate through the ResultSet to just put your ps.close(); after the while block
Edit:
do it something like this
public returnType methodname()
{
try{
//your boilerplate code
return whateverYouWantToReturn;
}
catch(AppropriateExceptionClass e)
{
e.printStackTrace();
}
finally
{
//closing statements
}
return null;
}
The execution of
ps.close();
is in the wrong place.
You have to close the Statement after having iterate on its result set (that is, just close ps after the while loop).
i've occours this strange error for the first time in my life, and i don't know what does it means. I've a class that retrieve information from a table on a postgresql database, do some operations and return an arraylist with parsed element:
ResultSet rs = ProduttoreDCS.getProduttori();
System.out.println("Recuperato result set produttori");
ArrayList<String[]> res = new ArrayList<String[]>();
while (rs.next()) {
String[] current = new String[6];
current[0] = Integer.toString(rs.getInt("partita_iva"));
current[1] = rs.getString("nome");
current[2] = rs.getString("cognome");
current[3] = rs.getString("via_sede");
current[4] = rs.getString("citta_sede");
current[5] = rs.getString("provincia_sede");
res.add(current);
current = null;
}
return res;
the error is on "while" line.
public static ResultSet getProduttori() throws ClassNotFoundException, SQLException {
/*
* retrieve all record from produttori table
*/
Connection conn = null;
ResultSet res = null;
Statement stmt = null;
String query = "SELECT * FROM produttore";
conn = ConnectionManager.getConnection();
System.out.println("Connection obtained by ProduttoreDCS class");
stmt = conn.createStatement();
res = stmt.executeQuery(query);
stmt.close();
conn.close();
return res;
}
I've encountered the same problem by running the wrong combination of:
Postgres version;
Hibernate dialect;
postgres jdbc driver;
Updating all to the latest version solved the problem for me.
P.S. I know this is not what OP was asking, but this is the first result in Google when you search for the problem.
when you close the connection object in your getProduttori method, your result set will be automatically closed. when you try to re use it , it will be null.
ResultSet rs = ProduttoreDCS.getProduttori();
= null, as you have closed the connection in getProduttori
method, which will automatically close the resultset
thus, it returns null.
From Connection#close
Releases this Connection object's database and JDBC resources
immediately instead of waiting for them to be automatically released.
applies same when closing the Statement as well.For your code to work don't close Statement and Connection untill you get the rows.
#Baadshah has already shown you the standard way. If you are using java 7+ you can make use of try-with-resource block, which would make your life simpler.
try(Connection conn = gettheconn){
get the statement here
get the result set
perform your ops
}
catch(SQLException ex){
ex.printstacktrace();
}
If you observe, there is no finally block, your connection object will be closed once you exit the try block automatically.you don't have to explicity call Connection#close()
As per Docs
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
You are closed the connection and then you are iterating ,where it is null.Please read the data and then close the connection.
A good practice here is
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn =
stmt = conn.prepareStatement("sql");
rs = stmt.executeQuery();
//DO SOME THING HERE
} catch {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
This is the problem:
stmt.close();
conn.close();
You're closing the connection to the database. You can't do that until you've read the data - otherwise how is the ResultSet going to read it? Maybe it will have read some data in to start with, but it's not meant to be a disconnected object.
In particular, from the docuemntation for ResultSet.close:
Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.
Closing the connection makes the resultSet go away.
A ResultSet is not a container you can use to pass data around in, it's only a wrapper around a cursor. You should run through the resultSet contents and copy them into a data structure, then return the data structure. You are already doing that, but you need to do it before closing the statement and connection.
Change the code to:
public static List<String[]> getProduttori() throws ClassNotFoundException, SQLException {
ArrayList<String[]> res = new ArrayList<String[]>();
/*
* retrieve all record from produttori table
*/
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
String query = "SELECT * FROM produttore";
conn = ConnectionManager.getConnection();
try {
System.out.println("Connection obtained by ProduttoreDCS class");
stmt = conn.createStatement();
try {
rs = stmt.executeQuery(query);
while (rs.next()) {
String[] current = new String[6];
current[0] = Integer.toString(rs.getInt("partita_iva"));
current[1] = rs.getString("nome");
current[2] = rs.getString("cognome");
current[3] = rs.getString("via_sede");
current[4] = rs.getString("citta_sede");
current[5] = rs.getString("provincia_sede");
res.add(current);
}
return res;
} finally {
try {
stmt.close();
} catch (SQLException e) {
log.error(e);
}
}
} finally {
try {
conn.close();
} catch (SQLException e) {
log.error(e);
}
}
}