Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,208,189 members, 8,001,845 topics. Date: Wednesday, 13 November 2024 at 05:19 PM

Java JDBC Resultset.next PROBLEM - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Java JDBC Resultset.next PROBLEM (1731 Views)

How Will I Instal Jdbc Mysql In Eclipse / How Can Do This On A Java Derby Resultset / Java Jdbc (2) (3) (4)

(1) (Reply) (Go Down)

Java JDBC Resultset.next PROBLEM by Capnd143(m): 5:40pm On Aug 29, 2014
@javanian and all the pros in the house please help me out
i am having problem with navigating a jdbc, in created a button,
and i want the button to load the next record from a datase when clicked
but i keep getting a weird looking logical error when i try it out, this is my code:


private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try{while( rs.next( ));
int id_col = rs.getInt("ID"wink;
String first_name = rs.getString("First_Name"wink;
String last_name = rs.getString("Last_Name"wink;
String job = rs.getString("Job_Title"wink;
String id = Integer.toString( id_col );
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);}
catch(SQLException err){System.out.println(err.getMessage());}


this is the error i get when i run the the application:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Employees.Workers.btnNextActionPerformed(Workers.java:204)
at Employees.Workers.access$200(Workers.java:17)
at Employees.Workers$3.actionPerformed(Workers.java:138)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:703)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:676)
at java.awt.EventQueue$4.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:673)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
@javanian
@
@programmer
@seun
Re: Java JDBC Resultset.next PROBLEM by Javanian: 6:23pm On Aug 29, 2014
First of all, this is not a logical error, it is a run time error. You are most likely trying to utilize a variable you haven't initialized or a variable that points to null hence the 'NullPointerException'. I can't see the rest of your code but i suspect it is comming from the result set variable 'rs'. Check to see if it has been initialized and if it actually holds any value.
Re: Java JDBC Resultset.next PROBLEM by uken73(m): 3:11pm On Aug 30, 2014
Yes Null Pointer Exception indicates an attempt to access an uninitialized variable and like Javanian has already said, it's most likely the ResultSet rs. Confirm that it has been initialized.
Re: Java JDBC Resultset.next PROBLEM by Capnd143(m): 6:10pm On Aug 30, 2014
Javanian: First of all, this is not a logical error, it is a run time error. You are most likely trying to utilize a variable you haven't initialized or a variable that points to null hence the 'NullPointerException'. I can't see the rest of your code but i suspect it is comming from the result set variable 'rs'. Check to see if it has been initialized and if it actually holds any value.
you were right, i didnt initialize my ResultSet (rs) object variable thats why i got the NullPointerException, i fixed that by declaring and assigning values for my ResultSet variable under the
button press event, which i had to create a connection to the database each time the button is pressed rather than use a method, this is giving me undesired result :
E.g
//i am using mobile nw so excuse
//my bad formating and syntax

btnNextActionPerformed(java.awt....){
try {
String host="jdbc:derby://localhost:1527/Employees";
String uName="admin1";
String uPass="admin";
connection cont =DriverManager.getConnection(host,uName,uPass);
Statement stmtt= cont.CreateStatement();
String SQL="SELECT * FROM Workers";
ResultSet rs3=stmtt.executeQuery(SQL);
while (rs3.next())
{


//get value
string fname=rs3.getString(Fname);
//set value
txtFirstName.setText(fname);
}
cont.close();
}
//catch some Exception here
catch(){}

======
==
all this code does is return the last record from my data table probably due to the while loop (i tried if,esle statement too, didnt work either)

i want to go step by step throw my data table and retrieve the value at the current cursor position and set those values as the value of a text field...
Am dying here please
|help out a newbie|
Re: Java JDBC Resultset.next PROBLEM by Capnd143(m): 6:14pm On Aug 30, 2014
uken73: Yes Null Pointer Exception indicates an attempt to access an uninitialized variable and like Javanian has already said, it's most likely the ResultSet rs. Confirm that it has been initialized.
please help me check the code above! Thanks
Re: Java JDBC Resultset.next PROBLEM by Javanian: 6:47pm On Aug 30, 2014
OKAY, Let's start. cheesy

First of all, It is imperative for you to know that creating a connection each time a button is clicked is wrong in every way possible. You should put your connection statements in a method and place it in your constructor. So it establishes a connection as soon as the application starts.

So assuming the method is called InitDatbase()

Your code should be something like

void InitDatabase()
{

try
{
String host="jdbc:derby://localhost:1527/Employees";
String uName="admin1";
String uPass="admin";
connection cont =DriverManager.getConnection(host,uName,uPass);
Statement stmtt= cont.CreateStatement();
String SQL="SELECT * FROM Workers";
ResultSet rs3=stmtt.executeQuery(SQL);
}
}


Then you call your InitDatabase() in your constructor like this

  public YourClassName
{
InitDatabase();
}


Okay, i don't really know how you intend to make your app work. So i will touch a possible scenario i can think of. I am going to assume that as soon as the app loads it displays the first user in the database. To do this, you should create a method somewhere and probably call it firstUser();

In your first user method, do this.

void firstUser()
{
try
{
rs3.first();
//get value
string fname=rs3.getString(Fname);
//set value
txtFirstName.setText(fname);
}

}
Now in your btnNextActionPerformed method, do something like this. This would work for the 'NextUserButton'

try
{
rs3.next();
//get value
string fname=rs3.getString(Fname);
//set value
txtFirstName.setText(fname);
}
Re: Java JDBC Resultset.next PROBLEM by uken73(m): 8:08pm On Aug 30, 2014
Capnd143: please help me check the code above! Thanks
Check the Javanian's recommendation. That's the logical way to go.

The summary of the recommendation is, you pre-load your data say in the constructor.
You now have the data in the Resultset and can make it to start up with displaying the 1st Record in the list.
Then you fetch the next record from the ResultSet by moving the cursor on an ActionEvent of your Next button.
So each time the mouse is clicked, the cursor is advanced one step to fetch the next record.

However, to add to that,

There should also be provision to close the database connection so as to release the scarce resource.
That should be "cont.close();" as the last statement after ResultSet rs3=stmtt.executeQuery(SQL); in the InitDatabase() method.
I also think Javanian missed the catch handler section for the try blocks including that of the InitDatabase method.
I would have declared my connection before the try block without initialization, so that I can have access to the variable in the catch handler section of the try block. That would be the best place to close the database connection.

Note; It's been years since I last handled a project with Java, I may have missed some other things.
Re: Java JDBC Resultset.next PROBLEM by Capnd143(m): 3:06pm On Sep 01, 2014


//ok i guess i am starting to be a pain in the ass around here, but i seriously am not getting it,
//i have never been stucked so long in a particular problem, its been 4 days now, i have done virtually everything am
// told but keep getting undesired results, dunno whether its related to my java version or what, so am posting my entire code here



//sturborn code begins here


public class Workers extends javax.swing.JFrame {



public Workers() {
initComponents();
DoConnect();
}
void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "admin1";
String uPass= "admin";

Connection cont = DriverManager.getConnection( host, uName, uPass);

Statement stmtt = cont.createStatement();
String SQL = "SELECT * FROM Workers";
ResultSet rs2 = stmtt.executeQuery(SQL);
rs2.next( );
int id_col = rs2.getInt("ID"wink;
String first_name = rs2.getString("First_Name"wink;
String last_name = rs2.getString("Last_Name"wink;
String job = rs2.getString("Job_Title"wink;
String id = Integer.toString( id_col );
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);


}


catch ( SQLException err ) {
System.out.println( err.getMessage( ) );

}
}

// crazy button to handle the database naigation begins here
//=======================================================================================//

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {

try
{



if( rs3.next()) //for some crazy reason my netbeans underlines my rs3 object variable
//and keeps shouting "cannot find symbol"
{ //when i know so well i declared that variable
int id_col = rs3.getInt("ID"wink;
String first_name = rs3.getString("First_Name"wink;
String last_name = rs3.getString("Last_Name"wink;
String job = rs3.getString("Job_Title"wink;
String id = Integer.toString( id_col );


textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);

}

cont.close();
}

catch(SQLException err) {System.out.println(err.getMessage());}


}





Re: Java JDBC Resultset.next PROBLEM by Capnd143(m): 3:30pm On Sep 01, 2014
Javanian: OKAY, Let's start. cheesy

First of all, It is imperative for you to know that creating a connection each time a button is clicked is wrong in every way possible. You should put your connection statements in a method and place it in your constructor. So it establishes a connection as soon as the application starts.

So assuming the method is called InitDatbase()

Your code should be something like

void InitDatabase()
{

try
{
String host="jdbc:derby://localhost:1527/Employees";
String uName="admin1";
String uPass="admin";
connection cont =DriverManager.getConnection(host,uName,uPass);
Statement stmtt= cont.CreateStatement();
String SQL="SELECT * FROM Workers";
ResultSet rs3=stmtt.executeQuery(SQL);
}
}


Then you call your InitDatabase() in your constructor like this

  public YourClassName
{
InitDatabase();
}


Okay, i don't really know how you intend to make your app work. So i will touch a possible scenario i can think of. I am going to assume that as soon as the app loads it displays the first user in the database. To do this, you should create a method somewhere and probably call it firstUser();

In your first user method, do this.

void firstUser()
{
try
{
rs3.first();
//get value
string fname=rs3.getString(Fname);
//set value
txtFirstName.setText(fname);
}

}
Now in your btnNextActionPerformed method, do something like this. This would work for the 'NextUserButton'

try
{
rs3.next();
//get value
string fname=rs3.getString(Fname);
//set value
txtFirstName.setText(fname);
}


Capnd143:

//ok i guess i am starting to be a pain in the ass around here, but i seriously am not getting it,
//i have never been stucked so long in a particular problem, its been 4 days now, i have done virtually everything am
// told but keep getting undesired results, dunno whether its related to my java version or what, so am posting my entire code here
//sturborn code begins here
public class Workers extends javax.swing.JFrame {
public Workers() {
initComponents();
DoConnect();
}
void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "admin1";
String uPass= "admin";
Connection cont = DriverManager.getConnection( host, uName, uPass);
Statement stmtt = cont.createStatement();
String SQL = "SELECT * FROM Workers";
ResultSet rs2 = stmtt.executeQuery(SQL);
rs2.next( );
int id_col = rs2.getInt("ID"wink;
String first_name = rs2.getString("First_Name"wink;
String last_name = rs2.getString("Last_Name"wink;
String job = rs2.getString("Job_Title"wink;
String id = Integer.toString( id_col );
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
}
// crazy button to handle the database naigation begins here
//=======================================================================================//
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try
{
if( rs3.next()) //for some crazy reason my netbeans underlines my rs3 object variable
//and keeps shouting "cannot find symbol"
{ //when i know so well i declared that variable
int id_col = rs3.getInt("ID"wink;
String first_name = rs3.getString("First_Name"wink;
String last_name = rs3.getString("Last_Name"wink;
String job = rs3.getString("Job_Title"wink;
String id = Integer.toString( id_col );
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
cont.close();
}
catch(SQLException err) {System.out.println(err.getMessage());}
}
Re: Java JDBC Resultset.next PROBLEM by uken73(m): 1:25am On Sep 03, 2014
I currently don't have a Java compatible editor on my system to assist me with syntacs errors but I made some modification on your codes with comments and emphasis on the modifications. I hope this solves your problem.

public class Workers extends javax.swing.JFrame 
{
ResultSet rs2; //moved here to increase it level of access so that it can be
// available in the btnNextActionPerformed event method
public Workers() {
initComponents();
DoConnect();
}
void DoConnect( ) {
Connection cont; //move here to make it available in the catch block for closing
try{
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "admin1";
String uPass= "admin";
cont = DriverManager.getConnection( host, uName, uPass); //declaration moved outside try block
Statement stmtt = cont.createStatement();
String SQL = "SELECT * FROM Workers";
rs2 = stmtt.executeQuery(SQL); //declaration moved to class field
rs2.next( );
int id_col = rs2.getInt("ID" ) ;
String first_name = rs2.getString("First_Name" ) ;
String last_name = rs2.getString("Last_Name" ) ;
String job = rs2.getString("Job_Title" ) ;
String id = Integer.toString( id_col ) ;
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
catch ( SQLException err ) {System.out.println( err.getMessage( ) ); }
}
finally{cont.close();}//finally block introduced to handle closing of database connection.

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try
{
//rs3 for which I couldn't find it's declaration has been renamed to rs2
//to correspond to rs2 declared as data member
if( rs2.next())
{
int id_col = rs2.getInt("ID" ) ;
String first_name = rs2.getString("First_Name" ) ;
String last_name = rs2.getString("Last_Name" ) ;
String job = rs2.getString("Job_Title" ) ;
String id = Integer.toString( id_col) ;
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
//cont.close(); moved to finally block in DoConnect method.
}
catch(SQLException err) {System.out.println(err.getMessage());}
}
}


Notice that I enclosed the code segment in [code][/code] tags so that it can be formatted well for ease of reading the code.
Re: Java JDBC Resultset.next PROBLEM by Capnd143(m): 1:02am On Sep 04, 2014
uken73: I currently don't have a Java compatible editor on my system to assist me with syntacs errors but I made some modification on your codes with comments and emphasis on the modifications. I hope this solves your problem.

public class Workers extends javax.swing.JFrame 
{
ResultSet rs2; //moved here to increase it level of access so that it can be
// available in the btnNextActionPerformed event method
public Workers() {
initComponents();
DoConnect();
}
void DoConnect( ) {
Connection cont; //move here to make it available in the catch block for closing
try{
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "admin1";
String uPass= "admin";
cont = DriverManager.getConnection( host, uName, uPass); //declaration moved outside try block
Statement stmtt = cont.createStatement();
String SQL = "SELECT * FROM Workers";
rs2 = stmtt.executeQuery(SQL); //declaration moved to class field
rs2.next( );
int id_col = rs2.getInt("ID" ) ;
String first_name = rs2.getString("First_Name" ) ;
String last_name = rs2.getString("Last_Name" ) ;
String job = rs2.getString("Job_Title" ) ;
String id = Integer.toString( id_col ) ;
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
catch ( SQLException err ) {System.out.println( err.getMessage( ) ); }
}
finally{cont.close();}//finally block introduced to handle closing of database connection.

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try
{
//rs3 for which I couldn't find it's declaration has been renamed to rs2
//to correspond to rs2 declared as data member
if( rs2.next())
{
int id_col = rs2.getInt("ID" ) ;
String first_name = rs2.getString("First_Name" ) ;
String last_name = rs2.getString("Last_Name" ) ;
String job = rs2.getString("Job_Title" ) ;
String id = Integer.toString( id_col) ;
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
}
//cont.close(); moved to finally block in DoConnect method.
}
catch(SQLException err) {System.out.println(err.getMessage());}
}
}


Notice that I enclosed the code segment in [code][/code] tags so that it can be formatted well for ease of reading the code.
thanks bro, your explanation panned out right, thanks a lot!
Re: Java JDBC Resultset.next PROBLEM by uken73(m): 6:36pm On Sep 04, 2014
Capnd143: thanks bro, your explanation panned out right, thanks a lot!
I'm glad it was of help.
Re: Java JDBC Resultset.next PROBLEM by xxlbnero: 8:28pm On Oct 06, 2014
Capnd143:
@javanian and all the pros in the house please help me out
i am having problem with navigating a jdbc, in created a button,
and i want the button to load the next record from a datase when clicked
but i keep getting a weird looking logical error when i try it out, this is my code:


private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {
try{while( rs.next( ));
int id_col = rs.getInt("ID"wink;
String first_name = rs.getString("First_Name"wink;
String last_name = rs.getString("Last_Name"wink;
String job = rs.getString("Job_Title"wink;
String id = Integer.toString( id_col );
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);}
catch(SQLException err){System.out.println(err.getMessage());}


this is the error i get when i run the the application:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Employees.Workers.btnNextActionPerformed(Workers.java:204)
at Employees.Workers.access$200(Workers.java:17)
at Employees.Workers$3.actionPerformed(Workers.java:138)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:703)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:676)
at java.awt.EventQueue$4.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:673)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
@javanian
@
@programmer
@seun

this is a typical logic error ...
i will suggest you remove the semicolon at the line : try{while( rs.next( )); ...
that while loop is a condition that returns a boolean ( true / false ). Even though rs.next() is a call to a method ( next() ) which is usually preceded by a semicolon at every call, it is not true when used as a while loop sentinel. ...the semicolon included in the while condition automatically makes it a statement .

(1) (Reply)

Development Of An Android Game Using Unity3d Engine / In Need Of A PHP Mass Mailer Script / New Social Whot! and Snake Game For Android Phones

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 66
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.