Java ResultSet Skipping Records - java

After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.

Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}

Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}

public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.

Related

The resultset returns empty when connecting with MySQL

I'm trying to execute a query in database in MySQL using PreparedStatement and ResultSet.
The problem is that I am getting an empty result set in MySQL, otherwise I get a correct result on Derby.
Connection con= null;
ResultSet reslt =null;
PreparedStatement ps = null;
try
{
//Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SAIID","SAIID","SAIID");
//con = DriverManager.getConnection("jdbc:derby://localhost:1527/pavillons","saiid","saiid");
String Query =" SELECT * FROM ETUDIANT_PAV WHERE PAVILLONS = ? AND CHAMBRE = ? "
ps = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ps.setString(1, "A");
ps.setString(2, "1");
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
//System.out.println ("this is the query result"+thequeryresult);
JOptionPane.showMessageDialog(null, "Query Executed");
//con.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
Seeing this lines :
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
If you used that commented line to checked the result, this can't worked. You need to move the cursor of that result set to the first line (start to -1).
For that, use ResultSet.next() that will return true until there is no more row to read.
reslt = ps.executeQuery();
while(reslt.next()){ //read all lines
System.out.println(reslt.getString("NOM_PRENOM"));
}
String selctedItemPAV = indextostring(jComboBox1.getSelectedIndex());
String selctedItemCH = jList1.getSelectedValue();
String Query =" SELECT * FROM etudiant_pav WHERE PAVILLONS = ? AND CHAMBRE = ? " ;
rst = theSelectQuery(Query,selctedItemPAV ,selctedItemCH); //this is the posted function
DefaultListModel listModel = new DefaultListModel();
jList3.setModel(listModel);
System.out.println (selctedItemCH + " doppppppppp " +selctedItemPAV + jComboBox1.getSelectedIndex());
System.out.println ("doppppppppp222222222");
if (rst.isBeforeFirst())
{
System.out.println ("ttttttttttttttttttttttttttttttttttttttttttttt"); //the excution stops here in application.....
jList3.setEnabled(true);
listModel.clear();
jLabel1.setVisible(false);
while (rst.next())
{
String aff="hhh";
aff= rst.getString("NOM_PRENOM");
System.out.println ("dooooooooo"+aff);
listModel.addElement(aff);
}
}
else
{
jLabel1.setVisible(false);
jList3.setEnabled(false);
JOptionPane.showMessageDialog(null, "la chambre est vide ");
}
rst.close();
}
catch (Exception ex){
}

ResultSet not open although i have only one at a time

I know many questions were asked before for this issue but for this situations I can't find an answer.
This is my code:
private Collection<Coupon> getCouponsMain(Company company, String filters) throws DAOException
{
String sql = null;
if (filters != null)
{
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ? AND ?";
}
else
{
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ?";
}
try (Connection con = pool.OpenConnection(); PreparedStatement preparedStatement = con.prepareStatement(sql);)
{
// query command
preparedStatement.setLong(1, company.getId());
if (filters != null)
{
preparedStatement.setString(2, filters);
}
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
CouponDBDAO couponDao = new CouponDBDAO();
rs.previous();
return couponDao.BuildCoupons(rs);
}
else
{
return null;
}
}
catch (SQLException | NullPointerException e)
{
throw new DAOException("Failed to retrieve data for all coupons" + e.getMessage());
}
}
I think the query itself is not the important issue here but, once I use next() for the ResultSet, I get the error:
java.sql.SQLException: Operation not allowed after ResultSet closed"
This usually happened when using two rs for same statement, this is not the case this time.
Due to many issues with previous method and BuildCoupons(rs) issue, also this part does not work properly for the same reason:
#Override
public Company getCompany(long id) throws DAOException
{
String sql = "SELECT * FROM couponsystem.company WHERE ID = ?";
try (Connection con = pool.OpenConnection(); PreparedStatement preparedStatement = con.prepareStatement(sql);)
{
// query command
preparedStatement.setLong(1, id);
// query execution
ResultSet rs = preparedStatement.executeQuery();
Company comp = new Company();
if (rs.next())
{
//Fill customer object from Customer table
comp.setId(rs.getLong("ID"));
comp.setCompName(rs.getString("COMP_NAME"));
comp.setPassword(rs.getString("PASSWORD"));
comp.setEmail(rs.getString("EMAIL"));
comp.setCoupons(comp.getCoupons());
}
else
{
comp = null;
}
return comp;
}
catch (SQLException e)
{
throw new DAOException("Failed to retrieve data for customer id: " + id);
}
}
BTW - working with MySQL and insert, update and delete queries are working properly so there not issue with the connection to the db
Another update -
Once i replace it to regular statement, it's working but of course i'm losing all the advantages of prepared statement
Like i said i create new code in order to isolate the big program
This is the code:
public class testState
{
public static void main(String[] args) throws SQLException
{
DBDAO pool = DBDAO.getInstance();
String sql = "SELECT ID FROM couponsystem.company WHERE COMP_NAME = ? AND PASSWORD = ?";
String compName = "t";
String password = "t";
pool.CreatePool();
Connection con = pool.OpenConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, compName);
preparedStatement.setString(2, password);
preparedStatement.executeQuery();
ResultSet rs = preparedStatement.executeQuery();
System.out.println("rs status: " + rs.isClosed());
if (rs.next())
{
System.out.println("log-in was successfuly performed");
System.out.println(rs.getLong(1));
System.out.println("hjhjh");
}
else
{
System.out.println("-1");
}
rs.close();
preparedStatement.close();
con.close();
pool.CloseConnection();
}
}
Problem was solved,
this is the problem:
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ? AND ?";
the second ? is illegal, but the exception is ResultSet closed and not query issue
the problem is you are trying to go back to the previous record in the result set which is not possible.
learn about scrollable resultset and make it insensitive, once you use this you can go back to the previous record by using rs.previous()
ResultSet.TYPE_SCROLL_INSENSITIVE

Sequence.NEXTVAL in Oracle 12c with rs.getInt() or getLong() fails - so what datatype it returns?

I am fetching next value of sequence with the ps = connection.prepareStatement("select seq.nextval from dual");
But neither getLong() nor getInt() works.
So how to correctly get the value from the ResultSet then?
full code:
public static long seqGetNextValue(String sequence) {
Connection connection = Util.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
Long value = new Long(0);
try {
ps = connection.prepareStatement("select ? from dual");
ps.setString(1, sequence);
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}
return value;
}
The exception is below, for getInt it looks the same:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.CharCommonAccessor.getLong(CharCommonAccessor.java:258)
at oracle.jdbc.driver.T4CVarcharAccessor.getLong(T4CVarcharAccessor.java:562)
at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:228)
at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:620)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at util.Util.seqGetNextValue(Util.java:85)
PreparedStatements cannot bind object names, just values. If you attempt to bind seq.nextval as you're doing above, you're actually binding the string literal 'seq.nextval', so your code is effective doing the following:
SELECT 'seq.nextval' -- Note that this is a string!
FROM dual
Now it's obvious why getInt and getLong don't work - you aren't querying a number.
TL;DR - you cannot bind a sequence's name, and should just hard-code it in the statement (or use string manipulation/concatination to create the query). Once you've done that, you can use either getInt or getLong, depending on the values you expect to get. E.g.:
try {
ps = connection.prepareStatement("select " + sequence + " from dual");
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}

ResultSet search Error in JDBC

so I am a beginer in JDBC - SQL Programming. I need a little advice which is most probably about SYNTAX.
So, Problem = I'm trying to search a record which has name(string provided in function argument) in the record. Following is my code. Now I've designed this code in such a way that there can be more than 1 records with the same name, so all of that records' data will be printed (by ShowData() Function).
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
So here it is. As far as my understanding goes, there is some problem with either RESULTSET rs or the Query I'm executing.
Kindly help. & if you can suggest a better approach for search, sure do please. I'm going to write 4 more functions SearchbyAge, SearchbyQualification, SearchbySpecialization on the same pattern.
Just this is enough
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
You don't have to check the data in resultset this way with a if case
if( !(rs.next()) )
This will move to the next record in the resultset
SOVLED
My error was in query. I was putting spaces in string's syntax which I was comparing.
WRONG = `"(.. WHERE name = " ' +toCompareName+ '" ");
RIGHT = `"(.. WHERE name = "'+toCompareName+'" ");
So thats it. Hope it helps to anyone else. :)

resultset isn't going into while loop and set the value

Observing a strange behavior of this piece of code,because resultset is not giving the null value(doing SOP it's clear)but not going into while loop(that is quite strange!)and it's simple dao class,it's not able to set the value in user object:
public class DAO{
public List<User> searchAllUsers(int offset ,int noOfRecords, String column, String value){
String query="select SQL_CALC_FOUND_ROWS * from info where '"+column+"' like '%"+value+"%' order by serialNo asc limit " + offset + " , " + noOfRecords;
// String query="select * from info where '"+select+"' like '%"+search+"%' order by serialNo asc";
System.out.println("1");
List<User> list = new ArrayList<User>();
User user=null;
try {
System.out.println("b4 Connection");
connection = getConnection();
System.out.println("After Connection");
stmt = connection.createStatement();
System.out.println("Create statement");
ResultSet rs=stmt.executeQuery(query);
if(rs!=null)
System.out.println("1> Hi rs:"+rs);
while(rs!= null && rs.next()){
System.out.println("hi...!!");
user=new User();
user.setSerial(rs.getInt(1));
System.out.println("Serial : "+rs.getInt(1));
user.setName(rs.getString(2));
user.setEmail(rs.getString(3));
user.setImei(rs.getString(4));
System.out.println("I'm here !");
user.setModel(rs.getString(5));
user.setManufacturer(rs.getString(6));
user.setOsversion(rs.getString(7));
user.setHdyk(rs.getString(8));
user.setDate(rs.getString(9));
user.setAppname(rs.getString(10));
list.add(user);
System.out.println("Last..");
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
System.out.println("2> :" +rs);
if(rs.next()){
this.noOfRecords = rs.getInt(1);
System.out.println("3> :" +this.noOfRecords);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
And it corresponding output is :
1
b4 Connection
After Connection
Create statement
1> Hi rs:com.mysql.jdbc.JDBC4ResultSet#35e6e3
2> :com.mysql.jdbc.JDBC4ResultSet#c9630a
3> :0
Even I'm also using the same code like it for select All user's and that point of time I'm getting proper o/p.
Spending so many hours for it,but unable to resolve it-where I'm going wrong....so your review & comment will be always welcome.
That's because your query didn't fetch you any row. And hence rs.next() will return false, hence the execution will not go into the while loop:
while(rs!= null && rs.next())
And you don't have to check for rs != null. It won't be null. The stmt.executeQuery always returns a ResultSet. Just have rs.next() in your while:
while(rs.next())
And yes, you should use PreparedStatement for executing your query rather than Statement. Here's a tutorial which will help you get started.

Categories

Resources