Hi this is my java code for next button.
but it goes onto only 1 record i.e after the last record it moves to the 1st one only.
how to move it through the entire database entries.
plz provide me some suggestions.
public void Next() {
Connection con = null;
ResultSet rs = null;
try {
con = DBConnection();
PreparedStatement pstmt = con.prepareStatement("select * from data", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
if (rs.next()) {
field1.setText(rs.getString("Name"));
field2.setText(String.valueOf(rs.getInt("Age")));
} else {
rs.previous();
JOptionPane.showMessageDialog(nxtbtn, "end of file");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
rs.close();
} catch (SQLException err) {
JOptionPane.showMessageDialog(nxtbtn, err.getMessage());
// TODO: handle exception
}
}
}
When you call next, it reloads all the results from the database and moves the cursor to just before the first row, calling rs.next will move to the first row.
Do you're query once, presumably when you need to display the next record.
In your next method, simply call rs.next() to move the cursor to the next available row in the result set.
Of course, you'll need continue to manage the error states ;)
you need to get the resultset out side of the next() method. calling next() every-time resets the resultset, and cursor moves to start again.
if understand it correctly you want to use the next button to click throup the resultset?
then you shoul read the database an have it stored in your resultset outside the next button method.
at the moment it seems that your making a new resultset with every click and only reading the first set of data.
private Connection con = DBConnection();
private ResultSet rs = null;
private Statement stmt = null;
public void onLoad()
{
stmt = con.createStatement();
rs = stmt.executeQuery("YOUR-CODE-HERE");
}
and now in the next method go through the rs with each click
rs.next() move the cursor to the next available row.thats why it show one record. use while(rs.next())
Move one record forward like below
rs.next()
Move through all the 'next' records like below
while(rs.next())
Move back like below
rs.previous()
Related
I'm trying to display movie titles from the database, the problem is that if I call the rs.getString() method it always returns null. The database table is properly configured with one column/two rows and connected to the java application, so I don't know where the problem is..
This is my class which I call from the main function:
import java.sql.*;
public class Driver {
public Driver() {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
// DriverManager.registerDriver(new org.sqlite.JDBC());
c = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Movies");
rs.next();
System.out.println(rs.getString("title")); // <---- prints null
stmt.close();
c.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
3 things that seem weird:
you are using rs.next() before even using the first resultset.
it's not in a loop, meaning you'll only get the first result no matter how many rows there are
you are returning it in one string (getString) so I don't think it will return it properly.
Here's my code for the addStudent:
#FXML
private void addStudent(ActionEvent event) {
// sql query to insert data into students at ID, first name, last name, email and DOB
String sqlInsert = "INSERT INTO students(id,fname,lname,email,DOB) VALUES (?,?,?,?,?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlInsert);
// add the data in the right column
stmt.setString(1, this.id.getText());
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
And here's my code for removeStudent:
#FXML
private void removeStudent(ActionEvent event) {
try {
// sql query to delete data from the database
String sqlRemove = "DELETE FROM students WHERE id = ?";
// open a connection to the database and use PreparedStatement to
// initialize the query.
Connection conn = dbConnection.getConnection();
PreparedStatement delete = conn.prepareStatement(sqlRemove);
// information needed to delete the row
delete.setString(1, selectStudent());
// execute and delete
delete.executeUpdate();
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// update table after deleting
loadStudentData(event);
}
The picture above is the view of my table. I hit LoadData and my table values show up. I want to be able to click on a row(student) and hit Delete Student to remove it.
Helper method for removeStudent:
private String selectStudent() {
String result = "";
try {
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
result = rs.getString(1);
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return result;
}
I'm pretty sure it has to do with when I "click" on a row, the id value for that isn't being held anywhere so when I hit "Delete" nothing is being given for it to Delete.
I don't know. Any advice would be awesome. :D
First edit: nothing is assigned to delete.setString(1, this.id.getText()). When I click on the row and hit delete, nothing is happening because there's nothing being assigned to id when I click on the row. The query string DOES work however when I physically give it an ID to delete. Also verified that the button does work; it prints out a lovely message for me with a good ol' System.out.println("expletive");
Second edit: Ok, so I updated the removeStudent code and now all I get is the string "null" returned. Nothing deletes. Nothing updates. Nothing is happening except I get "null" in the console.
Third edit: Getting closer! With the realization that the removeStudent isn't being given an ID to delete, I decided to create a private helper method that will do a SELECT query. Now, when I hit delete, it'll delete....but from the top, and not at where I want it selected. The code is above.
Fourth edit: Getting even closer! So, I figured out how to capture the row I click on within the table and I can delete......however, because of my sqlRemove command, I'm deleting by id so if I click on a row with index 3, then ONLY the row within the table that has an id of 3 will be deleted, nothing else. I gotta re-write how the sqlRemove command is worded.
I fixed it:
private String selectStudent() {
// initial value for result to return
String result = "";
// grab the index of the row selected on the table
int initial = studenttable.getSelectionModel().getSelectedIndex();
try {
// SELECT query to execute
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
// while there's a next row
while(rs.next()) {
// set temp to equal the id rs.next() is currently on
String temp = rs.getString("id");
// get the row id - 1 since we start at 0
int temp1 = rs.getRow() - 1;
// if temp1 is equal to the index we selected
if(temp1 == initial) {
// make it equal to result
result = temp;
}
}
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// return the row to delete
return result;
}
What's going on is in the comments. I finally figured out how to pass the value from a selected row and compare it to a row. Once I get the correct row to pass, I give it to the delete function to remove.
After a day in a half.............but I love it, so. Yeah.
Hey guys I'm trying to scroll through the rows in my database. For some reason my previous and next buttons are not working. Next button displays just first row and previous button doesn't display anything. My first and last buttons are working.
private void previousbtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT * FROM EMPLOYEE");
if (rs.previous())
{
str1 = rs.getString("emp_id");
emp_id.setText(str1);
str2 = rs.getString("emp_fname");
first_name.setText(str2);
str3 = rs.getString("emp_lname");
last_name.setText(str3);
}
else
{
rs.next();
}
con.close();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(EmployeeGUI.this, err.getMessage());
}
}
private void nextbtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from employee");
if (rs.next())
{
str1 = rs.getString("emp_id");
emp_id.setText(str1);
str2 = rs.getString("emp_fname");
first_name.setText(str2);
str3 = rs.getString("emp_lname");
last_name.setText(str3);
}
else
{
rs.previous();
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(EmployeeGUI.this, err.getMessage());
}
}
Here's the javadoc for ResultSet and this is what it says:
A ResultSet object maintains a cursor pointing to its current row of
data. Initially the cursor is positioned before the first row. The
next method moves the cursor to the next row, and because it returns
false when there are no more rows in the ResultSet object, it can be
used in a while loop to iterate through the result set.
So, when you get the ResultSet object, it will always be placed before the previous row and hence, previous() will always return false.
Assuming you are trying to implement Pagination with these buttons, I would recommend having a look at MySQL SELECT documentation and use limit to get the rows, e.g.:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
You can use it with LIMIT i, 1 where i will increment with each click of next and decrement with each click of previous.
I want to use while(rs.next()) to traverse the UserInfo table. There are seven records in UserInfo table, but I only got the first record. After I had joined the codes of rs.getRow();, I got the result what I want.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
while(rs.next())
{
String strName="Name is "+rs.getString(3)+";";
String intAge="Age is "+rs.getInt(5)+";";
String strCompany="Company is "+rs.getString(4)+".<br>";
//int rowNum=rs.getRow();
out.println(strName+intAge+strCompany);
}
out.println("Succeed in visiting UserInfo table.");
}catch(SQLException e){
out.println("Failed to query.");
}
I don't want to use rs.getRow();. How should I deal with this problem?
Your code does appear to be fine except the String part.If you are using String to hold a record, then you wouldn't be able to display all 7 records.
Thus try using collection object like ArrayList. And of course you should close connections in finally block.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
List<String> list = new ArrayList<String>();
while(rs.next()){
list.add(rs.getString(3));
}
System.out.println("rows "+list.size());
}catch(SQLException e){
out.println("exception "+e.getMessage());
}
finally{
rs.close();
stmt.close();
conn.close();
}
This is good example of how you should be retrieving values from database using collection object.
http://theopentutorials.com/tutorials/java/jdbc/how-to-retrieve-all-rows-from-mysql-table-using-jdbc/
rs.next() Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row;
rs.next only tells you if there is a next record.
When you run
ResultSet rs=stmt.executeQuery(queryStr);
This already places the data from the first record into variable rs.
In order to advance to the next record you need to run rs.getRow but only if there is a
next record (check with rs.next).
I'm trying to scroll over all the contents of a database. How do I properly do this:
conc conclass = new conc();
Connection conn = conclass.dbConnect();
try{
Statement statement=conn.createStatement();
ResultSet rs;
String sql;
rs=statement.executeQuery("SELECT * FROM q_table");
if(rs.next()){
String yo=rs.getString("Question");
jTextArea1.setText(yo);
}
}catch(Exception e){e.printStackTrace();}
And here's my class for connecting to the database:
public Connection dbConnect() {
try {
String db_connect_string="jdbc:mysql://localhost:3306/questions";
String db_userid="root";
String db_password="1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
What is wrong with my code? It loads the first record when I click on the scroll button. But when I click it again. It doesn't do anything at all.
To collect all results from table (I assume you mean the table rather than the whole database):
while(rs.next()) {
String yo=rs.getString("Question");
// add 'yo' to a list or similar...
}
You need to iterate across your ResultSet. The ResultSet scrolls over each row returned from the database in sequence. See this example for more details.
You need to keep the Resultset open. For every click on the button, you must call rs.next() once. After that, a new row will copied into the ResultSet.