I have a two database table, on a single button click in my program , I want to delete all the two table's data. But there's always one datum left on the table.. Here is my code:
public void mouseClicked(MouseEvent arg0) {
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete the log? ", "Log", JOptionPane.YES_NO_OPTION );
if (confirm == JOptionPane.YES_OPTION){
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:RIM");
Statement st1 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement st2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from userLogIn";
ResultSet rs1 = st1.executeQuery(sql1);
String sql2 = "select * from userViewed";
ResultSet rs2 = st2.executeQuery(sql2);
while(rs1.next()){
rs1.deleteRow();
rs1.first();
}
while(rs2.next()){
rs2.deleteRow();
rs2.first();
}
editorPane.setText("");
}catch(Exception e){e.printStackTrace();}
When there is only one element left, your call to first() sets the cursor to that element, but then the next() call in the while condition will return false, causing the exit from the loop and thus the deleteRow won't be executed.
Use rs.beforeFirst()`.
Note that your code has lots of issues, so get this answers as "for educational purposes" only.
Why are you iterating over a select record set at all? It's incredibly inefficient.
If you want to delete all data from those tables, you can simply execute the statements:
delete from userLogin;
delete from userViewed;
(or use truncate).
Related
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
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.
Using Java and MySQL, the while loop only returns the last record that satisfies the query. The query appears to be correct based on running it in MySQL Workbench. There should be more than one record being returned.
Statement statement2 = connection.createStatement();
String entryCrew = crewFlight.getText();
String s2 = "select airemployee.eid, airemployee.Fname, airemployee.lname, airemployee.phone, airemployee.JobDescription, airemployee.AircraftID, airemployee.salary, flightno\n" +
"from airemployee inner join flight on airemployee.aircraftID = flight.aircraftID where flightno = '"+entryCrew+"'";
ResultSet rs2 = statement2.executeQuery(s2);
while (rs2.next()){
outputArea.setText("EID:"+rs2.getInt("EID")+"---"+"First Name:"+rs2.getString("FName")+"---"+"Last Name:"+rs2.getString("LName")+"---"+"Phone:"+rs2.getString("Phone")+"---"+"Job:"+rs2.getString("JobDescription")+"---"+"AircraftID:"+rs2.getInt("AircraftID")+"---"+"Salary:"+rs2.getInt("Salary"));
}
}
catch (Exception exc){
JOptionPane.showMessageDialog(null, exc);
}
}
setText does not accumulate. Every step in the while loop overwrites what is there, leaving only the final record data at the end.
Collect into a StringBuffer and set at the end.
I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
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.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
I have two tables. And these tables have the same schema consisting of userid, username. I want to check is there any common username in table1 and table2.
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
My logic is:
while(rs1.next())
compare the value of rs1 with every value of rs2.
If there match found print one of the value else print both the values.
Is there a way to achieve this in java... Please anyone help me ... Thanks...
I would use a single SQL statement:
select table1.username from table1, table2 where table1.username = table2.username
This will only return usernames that appear in both tables, so no post-processing will be needed.
This construct is called an inner join. If you also want to identify usernames that are unique to table1 and/or table2, you could use an outer join.
You can either solve it through SQL statement IN and NOT IN or you can try something like this:
public boolean compareResultSets(ResultSet resultSet1, ResultSet resultSet2) throws SQLException{
while (resultSet1.next()) {
resultSet2.next();
ResultSetMetaData resultSetMetaData = resultSet1.getMetaData();
int count = resultSetMetaData.getColumnCount();
for (int i = 1; i <= count; i++) {
if (!resultSet1.getObject(i).equals(resultSet2.getObject(i))) {
return false;
}
}
}
return true;
}
Pseudo-Code:
if ( A.type = B.type )
{
PRINT same type
if ( A.format = B.format )
{
PRINT same format
if ( A.value = B.value )
{
PRINT same value
}
else
{
PRINT different value
}
}
else
{
PRINT different format
}
}
else
{
PRINT different type
}
One way could be:-
String query = "(" + query1 +") intersect ("+ query2 + ")";
Where in the intersect operation will anyway give you the common columns.
P.S. :- I know this question is old, but it might help somebody.
I am giving an example to solve this:
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
while(rs1.next()) {
// Compare till rs1 reachs its last record.
while(rs2.next()) {
if() {
// Do your code here...
}
}
// this will move resultSet cursor to the first position.
rs2.first();
}
This answer is already given by Akash5288 and Edited by Pavel Smirnov. And this worked for me like magic. I don't have access to Like or Comment on the original answer, that's why I am re-posting it. Thanks a lot. Just one edit from my side: rs2.beforeFirst(); will work better than rs2.first();.
I am giving an example to solve this:
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
while(rs1.next()) {
// Compare till rs1 reachs its last record.
while(rs2.next()) {
if() {
// Do your code here...
}
}
// this will move resultSet cursor to the first position.
rs2.first();
}