private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String del_user = JOptionPane.showInputDialog(null,"Enter the Username To be deleted :" ,"Delete User !", JOptionPane.WARNING_MESSAGE);
try {
stmt = con.createStatement();
String quer = "delete from Udet where username='"+del_user+"'";
rs=stmt.executeQuery(quer);
int count=0;
while(rs.next())
{
count++;
}
if(count==1)
{
JOptionPane.showMessageDialog(null,"The user has been deleted");
}
else
{
JOptionPane.showMessageDialog(null,"No such User Exists");
}
} catch(Exception e){}
}
THE QUERY EXECUTES FINE ! THE RECORD GETS DELETED BUT THE LINES AFTER QUERYEXECUTION ARE NOT EXECUTING ...
the JOptionPane will work after the try block but then the value of count wont be determined...
A DELETE statement doesn't return a ResultSet and therefore you should use the method stmt.executeUpdate(quer); instead of stmt.executeQuery(quer);.
One way you can see how many results were deleted from the query is run a SELECT COUNT(*) query on the table before and after the DELETE using the executeQuery() method which will both times return a ResultSet with a single result containing how many records the table contains. After running it before and after the DELETE you can compare the 2 numbers.
The result will probably be a String but you can just use int integer = Integer.parseInt(String); to get the int from it. The code should look like this:
stmt = "SELECT COUNT(*) AS Count FROM table_name";
int initialSize = 0;
rs = stmt.executeQuery(stmt);
while(rs.next){
initialSize = Integer.parseInt(rs.getString("Count");
}
Run the DELETE query and then repeat the COUNT query passing the int into a new variable (for this answer I'll call it newSize) so the number of changes the DELETE made would be:
int changesMade = initialSize - newSize;
Related
I am attempting to write a method that selects 2 entries into an employee database and removes them (Based on a salary field), I am currently using a counter to accomplish this, however I tried using setMaxRows() so my result set would only have two entries, thus eliminating the need for the counter. I am using try-with-resources to create my statement and that seems to be causing an issue.
public void downSize(Connection con) {
String sql = "SELECT * FROM " + schemaName + "."+tableName+" WHERE EMPLOYEE_SALARY>200000";
try (
PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = statement.executeQuery();
)
{
int counter = 0;
System.out.println("Now pruning workforce...");
while(rs.next() && counter<2) {
String name = rs.getString("EMPLOYEE_NAME");
rs.deleteRow();
counter++;
System.out.println(name+" was laid off.");
}
} catch(Exception e) {
e.printStackTrace();
System.out.print("Sql exception happened");
}
}
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.
I am trying to make a username only register if that name is not taken, using JDBC connection and checking on SQL Database.
I have the code that checks for the
SELECT * FROM user
WHERE username = 'jessica';
and it finds 2 rows;
Searched a lot and found that with getFetchSize() it would give me the number of rows, and if it finds null it would return 0.
It is always returning 0, I don't know why, because I have the usernames taken twice, it lets me add me always...
https://prnt.sc/galyqo
public int nameAvailable(MyUserApp app, String name) throws SQLException{
String sql = "SELECT * FROM user \n WHERE username = '"+ name +"';";
Statement st = app.getCon().createStatement();
ResultSet rs = st.executeQuery(sql);
int numResults = rs.getFetchSize();
return numResults;
}
This is the register code:
private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String username, password, address, dob;
boolean status;
String u;
try {
username = newUsernameField.getText();
password = passwordField2.getText();
address = addressField.getText();
dob = dateofbField.getText();
int no= 5;
if( username.isEmpty() || password.isEmpty() || password.length() < 6 ){
jLabel6.setText("The information you typed in is not valid. ");
status = false;
showTableDB.setText(""+status);
}
else{
no = this.app.nameAvailable(app, username);
jLabel6.setText(no+"");
if(no == 0){
jLabel6.setText("Registered your account, "+username+"!" + no);
status = this.app.registerUser(app, username, password, dob, address);
u = this.app.showInfo(app, username);
showTableDB.setText(u);
no = this.app.nameAvailable(app, username);
}
else{
showTableDB.setText("That username is token. Please choose a different one.");
}
}
} catch (SQLException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
The fetch size is not the same thing as the number of rows. The fetch size is just a way of limiting how many rows at a time will be fetched from the database.
There's no easy way to check the number of rows returned by a select statement. If you really need to know how many rows there are, in the case there's more than one, then one approach would be to iterate through the result set, copying the information that you need from each row into memory; then check the amount of data that you copied at the end.
Alternatively, if you don't actually need any data from the rows themselves, you could try a statement like SELECT count(*) FROM user WHERE username = ?.
One more thing - you need to read about SQL injection attacks. This is where a hacker uses your code to run SQL that they shouldn't. The code you've shown here is vulnerable to an SQL injection attack. But that's another question entirely.
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
I am still a beginner in Java and stackoverflow.
I coded a plugin for a minecraft server in java, using mysql for a stats system (Kills deaths points)
I want to know, how i can get the player with the highest amount of "Points", so i like to get the "Playername" where "Points" is the highest.
I also would like to get the 2nd highest, 3rd highest etc.
I used prepared statements like:
public static int getPoints(String Playername) {
int Points = 0;
try {
PreparedStatement st = con
.prepareStatement("SELECT Points FROM FFA WHERE UUID = '"
+ PlayerUtil.getUUID(Playername) + "'");
ResultSet rs = st.executeQuery();
if (rs.next()) {
Points = rs.getInt("Points");
} else {
Points = 0;
}
} catch (SQLException e) {
e.printStackTrace();
}
return Points;
}
If you are able to help me, that would be extremely nice!
Thanks for your time!
PS:
My SQL structure:
Playername varchar(64)
UUID varchar(64)
Kills int
Deaths int
Points int
You can use the following statement to do that:
select playername from FFA order by points desc limit 10;
That will return the top 10 players
Or you could do something like
select playername from FFA where points >= 1337 order by points DESC;
Then you can go through every entry calling rs.next() in a loop. First fetch with rs.next() will get you the player with more points because you used order by.
So the code would look like this:
public static String getTopPlayer() {
int limit = 10;
try {
preparedstatement st = con
.preparestatement("select * from FF order by points desc limit "
+ limit);
resultset rs = st.executequery();
if (rs.next()) {
name = rs.getString("playername");
//if rs.next() rs.getString("playername"); <-- returns second
//if rs.next(); rs.getString("playername"); <-- returns third
} else {
name = null;
}
} catch (sqlexception e) {
e.printstacktrace();
}
return name;
You can try something like this in SQL :
select playername from FFA where points=(select max(points) from FFA);
This query can return more than one row...
I am trying to delete a row from the database, but the control always goes into the else part below. I tried to execute the same delete statement on the database and it worked there.
I have verified all the column names and the table name are correct.
Can someone guide if I am doing anything wrong here?
Thanks.
public String delAd(String x, String y, String z){
String result = "";
int rowcount = 0;
try{
PreparedStatement ps = con.prepareStatement("DELETE FROM dbname.tablename WHERE iname = ? AND idesc = ? AND seller = ?");
ps.setString(1,x);
ps.setString(2,y);
ps.setString(3,z);
rowcount = ps.executeUpdate();
if(rowcount > 0){
result = "true";
System.out.println("Delete Successful");
}else{
result = "false: Value could not be deleted from the database";
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Check in your table if there is any row which satifies the query. simple way to test is do a select statement with the values live below.
SELECT * FROM TABLENAME WHERE INAME='WATEVER' AND IDESC='WATEVER';
it is obvious from the output that there are no rows that are satisfying your query thats why control is jumping to else.