Java Sql Exception After End of Result Set - mysql

My code works fine but when I try to run the code it first shows java.sql.SQLException:After end of result set. I would like to know what is causing this and how to fix this as this is for a graded project.
public GenerateBill()
{
initComponents();
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore","root","root");
Statement stmt=(Statement)con.createStatement();
String query, product;
query="select * from store;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next());
{
product=rs.getString("productname");
jComboBox1.addItem(product);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
}
When I execute the code a Message Dialog Box shows up first.
And when I click OK, the page I'm trying to make opens and executes normally.
So, I'm confused as to what it means. Also, I'm new to this site, so I don't really know how much of the code I need to add. The rest of the code is for different jButtons. The page is for Generating Bills/Receipts.

There are some parts in your code that could be better. Specifically,
Use com.mysql.jdbc.Driver as your DB is MySQL, instead of java.sql.DriverManager
No need to cast your Connection object.
After /bookstore you could add ?useSSL=false, although it is not mandatory, so something like jdbc:mysql://localhost:3306/bookstore?useSSL=false
Use java.sql.PreparedStatement instead of simply Statement.
Close your connection in a finally block after catch.
Eventually, your code should look somehow like the following,
public GenerateBill() {
initComponents();
Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?useSSL=false","root","root");
String query = "select * from store";
stmt = con.prepareStatement(query);
String product;
rs = stmt.executeQuery();
while(rs.next())
{
product = rs.getString("productname");
jComboBox1.addItem(product);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.toString());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
LOG.error("Error closing the connection with the database...");
e.printStackTrace();
}
}
}
Try the above and let me know if it is OK. If not, please post the whole exception to see what causes the issue.

Related

Does h2 have a query/clause similar to the WHERE IN in MySQL?

My code currently goes as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
String[] data = parentIds.toArray(new String[parentIds.size()]);
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (?)";
stmt = conn.prepareStatement(sql);
data = parentIds.toArray(data);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
However even though in the unit tests I try to pass an array with parentIds, the return remains null.
What I can gauge from this is one of the following:
The array data isn't getting properly read, therefore the output is coming as null.
WHERE IN is not supported by h2 or else there is a different implementation that needs to be used instead.
Where am I going wrong in this?
EDIT - There was a similar duplicate question that was tagged. While it suggested using a StringBuilder and a loop, I was looking for an answer stating how it could be done in a cleaner way using the query itself.
Try setting the parameter as a list instead of an array, ie replace
stmt.setObject(1, data);
with
stmt.setObject(1, Arrays.asList(data));
Figured it out.
There was an issue posted on the h2database GitHub about this exact problem. Followed the suggested edits and it worked!
Code after edits is as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
Object[] data = parentIds.toArray();
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (SELECT * FROM TABLE(x VARCHAR = ?))";
stmt = conn.prepareStatement(sql);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
As you can see, I've used an Object array for data instead and added an additional query inside the main query.
Followed the instructions given in the GitHub issue to a tee and it worked flawlessly.

SQL result convert into integer

I'm having trouble convert this String sql results into int. Can you guys tell how to accomplish this.
I'm doing this because I need this value set in to a JLabel that shows attendance count.
I've tried to search for the answer here, but I couldn't find it. Please can you guys help me with this problem?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
This is what I need to accomplish.
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
Or is there another way to accomplish this without doing this way?
Thanks.
get ResultSet.getInt(1):
int id = rst.getInt(1);
You could use ResultSet.getInt() method. It takes either a column index or a column name. Here's an example from Oracle.
In your case you would need the one which takes the index (note that index starts with 1, not 0).
As suggested earlier, try using .getInt() method.
Moreover, I would use PreparedStatement. It's important to use PreparedStatement, because it allows database to cache your queries.
Also, always close your Connection and ResultSet after using them.
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}

how to see new inserted data in textbox ? (java netbeans mysql)

I have a MySQL database in NetBeans.
When I add new data in my database by insert button, I can see my new data in output windows (because I have a code to print all data in database), but I don't know why I can't see my new data in textboxes, it means when I navigate fields by next, previous buttons I can't see my new data !!!!!!
But, when I close the program and run it again, my textboxes show my new data !
What's reason???????
my Next button code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (rs.next()) {
int x = Integer.parseInt(rs.getString("id"));
String s = rs.getString("name");
String n = rs.getString("profession");
txtID.setText(Integer.toString(x));
txtName.setText(s);
txtProfession.setText(n);
} else {
rs.previous();
}
} catch (Exception e) {
System.out.println(e);
}
}
My insert button code :
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO sample (id,name,profession) VALUES ('"+txtID.getText()+"','"+txtName.getText()+"','"+txtProfession.getText()+"');");
st.executeQuery("Select * from sample");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Help me please.
assuming ResultSet rs is a class level variable, with in your method jButton3ActionPerformed() change the following
st.executeQuery("Select * from sample");
to
rs = st.executeQuery("Select * from sample");
one suggestion is, you should close your database resources once you fetch the data and you can construct your Collection to hold the data for further processing.
The pagination that you are trying to use is not good practice

How to get data from MYSQL database

I have a database named as "test" in which I have a table named as "first" which contains raw data, I want to get this table data. What should be the prepare statement I have to use in order to get data from table "first" ? Below is the code I am trying. Any help or guidance would be appreciable.
#Path("/database") // Specific URL
#GE
#Produces(MediaType.TEXT_PLAIN)
public String returnDB_Status() throws Exception {
PreparedStatement query = null;
String result = null;
Connection conn = null;
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();
result = "Data received : " + rs;
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return result;
}
and the source code used get a connection
public class mysql_prac {
private static DataSource mysql_prac = null;
private static Context context = null;
public static DataSource dbConn() throws Exception {
if (mysql_prac != null) {
return mysql_prac;
}
try {
if (context == null) {
context = new InitialContext();
}
mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF)
} catch (Exception e) {
e.printStackTrace();
}
return mysql_prac;
}
}
You must loop through the ResultSet to get the fields of each row. So I made the following edit together with some comments.Please notice the comments.
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row
while(rs.next()){
String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1'
result = "Data received : " + dbUserID;
System.out.println(result);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}

Retrieving data from mysql in Java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "parin");
Statement stmt=con.createStatement();
String query="Select * from Liblogin;";
ResultSet rs=stmt.executeQuery(query);
String username=rs.getString("username");
String password=rs.getString("password");
rs.close();
stmt.close();
con.close();
String enteredUsername=t1.getText().toString();
String enteredPassword = new String(t2.getText());
if(enteredUsername.contentEquals(username)&&enteredPassword.contentEquals(password))
{
Homepage a=new Homepage();
a.setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect name and password.");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
I am trying to retrieve my password and username from mysql database.But unable to do so because of some exception(Sql exception:Before start of result set.).
You need to call rs.first(); or rs.next(); before trying to read the values from a ResultSet row.
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#first%28%29
Calling rs.next(); is especially handy in a while-loop to process all the rows in the ResultSet.
// Get a result set from SQL query
while (rs.next()) {
// Process this row
}