PreparedStatement Delete in Java - java

I have written a code to delete a record in a MySQL database from my Java Program. It compiles and runs it successfully, but the record is still in the datbase. Any suggestions?
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form, "Do you like to delete the record for Student ID: " +
textField_16.getText() + " ?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
String mock = textField_16.getText();
String sql = "DELETE FROM mockexam WHERE MockID =?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, mock);
int val = prest.executeUpdate();
JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
}
}
catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
}
}
});
btnDelete.setBounds(45, 235, 89, 23);
panel_1.add(btnDelete);

You don't indicate what kind of DB you are running against (innoDB or MyISAM, etc) but if you are running against InnoDB, you need to have a commit() statement to commit the transaction after your executeUpdate(). Chances are you have something in your log that indicates that your transaction has been rolled back.
try {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form,
"Do you like to delete the record for Student ID: " + textField_16.getText() + " ?",
"Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
String sql = "DELETE FROM mockexam WHERE MockID =?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "MockID");
prest.executeUpdate();
con.commit();
JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
}
}
catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
}
You're also missing connection an PreparedStatement close() calls in a finally{} block to ensure that you don't have any leaks in your code.

prest.setString(1, "MockID");
You are looking for a MockID equal to MockID I assume you want to delete a entry with a certain ID use:
String mockID = "2"; //Set this however you want to set it.
prest.setString(1, mockID);
int val = prest.executeUpdate();
//Check val for what happened.

If no records match your criterion then the SQL will be deemed to have worked. Hence I'd be suspicious of the parameter. What's the type of the column in the database? Could it be a fixed length value and so not match "MockID"?

Related

Truncated incorrect DOUBLE value using DELETE statement

int d1;
String attribute = comboBox1.getSelectedItem().toString(); // a combo box
System.out.println(attribute);
String data = t.getText(); // a textfield
System.out.println(data);
if (attribute.equals("COURSE_ID")) {
IsNumber in = new IsNumber();
d1 = in.stringToInt(data);
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "DELETE FROM course WHERE ? = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, attribute);
statement.setInt(2, d1);
boolean rows = statement.execute();
if (rows == true) {
new ViewDatabase(user, name, pswrd);
System.out.println("COURSE_ID UNIT UPDATE SUCCESSFUL!");
frame.setVisible(false);
} else if (rows == false) {
JOptionPane.showMessageDialog(null, "Cannot find row!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
For this piece of code, whenever I try to run it, it returns "Data truncation: Truncated incorrect DOUBLE value: 'COURSE_ID'". I'm not sure what this is referring to and I searched and found some people saying that this error message is misleading, though I only found answers to selects, inserts, and updates, but not deletes.
I also turned off strict mode in MySQL, as advised from the internet, but to no avail.
You can't bind strings to actual column names in a prepared statement. So, the attribute column names must be hard-coded. One pattern which might work would be:
String sql = "";
if ("COL1".equals(attribute)) {
sql = "DELETE FROM course WHERE COL1 = ?";
}
else if ("COL2".equals(attribute)) {
sql = "DELETE FROM course WHERE COL2 = ?";
}
else {
sql = "DELETE FROM course WHERE COL3 = ?";
}
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);
boolean rows = statement.execute();

How to delete row from bound JTable?

I have a JTable bound to MySQL. I already have done code to insert data.
But i don't know how to delete.
I have this sample delete method that works in other simple projects.
public String deleteItem(String name) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Even when I worked with an unbound table I have done this remove row from jtable that did well for me.
But now its a table bound to MySQL and I can't find a way to delete row... already searched on the internet. Found nothing.
PS: i'm using netbeans. i right-clicked jtable > bind > elements , to bind table.
Oh, I found a way!
First, I changed my deleteItem method, to delete by id
ItemDAO.java
public String deleteItem(int ID_item) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where ID_Item = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, ID_item);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Then the action in delete button goes like this.
Form.java
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int column = 0; // get the first column which is ID_Item
int row = tableItem.getSelectedRow(); //get row selected by user
int value = (int) tableItem.getModel().getValueAt(row, column); // store ID_Item value
String answer = new ItemDAO().deleteItem(value); // call up deleteItem method
if(answer.equals("OK")) {
System.out.println("OK"); // just for test
itemList.clear(); // this is needed to update the bound table after Insert/Delete/Update etc
itemList.addAll(itemQuery.getResultList()); // same as above comment
}else{
System.out.println("ERROR"); // just for test.
}
Maybe isn't the most beautiful way to do it, but it works.

ResultSet.next() row counter fails to count

I'm trying to figure out why this won't count and show Rows: 2 when I enter "ashton" for username and "ashton" for password. In my database I inserted 2 entries of username and password.
Here's the screenshot of table:
Here's the GRAB file:
Here's my code:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String userNameEntered = userNameTxtField.getText().trim();
String passwordEntered = passwordTxtField.getText().trim();
if(userNameEntered.isEmpty() || passwordEntered.isEmpty()){
JOptionPane.showMessageDialog(this, "Please fill out all fields");
}
else{
String username = "jordan";
String password = "jordan";
String dbURL = "jdbc:derby://localhost:1527/JDBCSTUDY";
Connection myConnection = null;
ResultSet myRs = null;
String SQL = "SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?";
try {
myConnection = DriverManager.getConnection(dbURL,username,password);
JOptionPane.showMessageDialog(null, "Successfully Connected To Database");
PreparedStatement myPrepStmt = myConnection.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
myPrepStmt.setString(1,userNameEntered); //assigns a string value to the first ?
myPrepStmt.setString(2,passwordEntered); //assigns a string value to the second ?
myRs = myPrepStmt.executeQuery(); // executes the select query and stores it to myRs
if(myRs.next() == false){//next() method returns true if the select statement is satisfied or if query is valid
JOptionPane.showMessageDialog(this, "Not found");
}
int countRows = 0;
while(myRs.next()){
countRows++;
if((myRs.getString(2).equals(userNameEntered))
&& (myRs.getString(3).equals(passwordEntered))){
JOptionPane.showMessageDialog(this,"found" +"\nRows: " + countRows );
}
}
} //end of try
catch (SQLException e) {
//if an exception or an error even occured while executing the try{} block, the 3 lines will be printed
System.err.println("Error message: " + e.getMessage());
System.err.println("Error Code: " + e.getErrorCode());
System.err.println("SQL State: " + e.getSQLState());
}
finally{
if(myConnection!=null){
try {
myConnection.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,"Error encountered: " + ex.toString());
}
}//end of if
}//end of finally
}
}
In my understanding, next() returns true if the SELECT query is successful or if there are rows when cursor is moved by next(). I need to be able to count the rows to show that there are more than 1 row holding the same username and password. I can't proceed on making another ifelse for counting duplication of username and password because in my code, it doesn't seem to count 2 rows.
I'd appreciate any help.
Thanks.
this is the output i get,
This is what I did, and it worked. Thanks for the suggestions guys! It's helping me learn more.
int countRows = 0;
while(myRs.next()){
countRows++;
}
if(countRows == 0)
{
JOptionPane.showMessageDialog(this, "User details doesn't exist. \n Please register first");
}
else if(countRows > 1) //if there are duplications
{
JOptionPane.showMessageDialog(null, "User details found but has more 1 one entry" +
"\nFound: " + countRows + " users" );
}
else if(countRows == 1){
JOptionPane.showMessageDialog(null, "User Found");
}
Your error is to call rs.next twice: Every time you call next you are implicitly discarding the last state of the cursor. It's a good (and clearer) practice to read the resultset's columns after every call to next.
In your case, it's enough to move if after the while loop, changing the condition:
int countRows = 0;
while(myRs.next()){
countRows++;
...
}
if (countRows==0)
{
JOptionPane.showMessageDialog(this, "Not found");
}
The main problem is you call myRs.next() two times before getting data.
You can use
myRs.isBeforeFirst()
as described here
or use this template as described here
if (!myRs.next() ) {
System.out.println("no data");
} else {
do {
//statement(s)
} while (myRs.next());
}
And you don't need loop at all — just use a SQL request with count
SELECT COUNT(*) FROM USERS WHERE USERNAME = ? AND PASSWORD = ?

Retrieving data based on the ID java

i wanted to retrieve the data from the database with ID.. So, i wanted to do like this: i have number on my combobox 1 to 4. Whenever i select 1 in combobox, the textbox firstname and lastname text will be change based on the selected id. How do i do that?
I already tried like this, but it won't work:
private void Edit(Connection conn, Statement state, ResultSet result)
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String url = "jdbc:odbc:Database";
conn = DriverManager.getConnection(url);
String query = "select FirstName, LastName, Status, JoinedDate from Customer where ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, jComboBox1.getSelectedIndex());
result = statement.executeQuery();
while(result.next())
{
jTextField3.setText("FirstName");
jTextField2.setText("LastName");
jTextField3.setText("Status");
JoinedDateLabel.setText("JoinedDate");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
_sound.PlaySound(2);
_infoBox.ShowMessageBox(e.getMessage(), "Error", 2);
_reminder = new Reminder(1);
JOptionPane.showOptionDialog(null, "Program will be closed due to error!", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
System.exit(0);
}
Thank you
Try this
while(result.next())
{
jTextField1.setText(result.getString("FirstName"));
jTextField2.setText(result.getString("LastName"));
jTextField3.setText(result.getString("Status"));
JoinedDateLabel.setText(result.getString("JoinedDate"));
}
All you're doing with your current code is setting the text to the strng literal "FirstName". You need to actually retrieve the data from the ResultSet and set the text as that data.
Also, note JComboBox indices are 0 based. So if you are selecting the first index, it would return 0. You should make sure (in your case) that the db has Id's of 0,1,2,3

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

Categories