user5842257
user5842257

Reputation:

Deleting row in database

I want to delete the row which selected from JTable from database I have checked that my java program is connected to database but i am confused how to delete entire row from ms access database without affecting or touching any column just wanted to delete the selected row in jtable

My database consists of 8 columns full name, father name, father cnic, date of birth, class, address, city and province

int x = MyTable.getSelectedRow();
String b = String.valueOf(MyTable.getValueAt(x, 1)); 

try {
     Connection con;
     Statement stmt;


    Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
    con =DriverManager.getConnection("jdbc:ucanaccess://C://Users//abdul//Desktop/StudentDatabase.accdb");


    stmt = con.createStatement();

    stmt.executeUpdate("delete from StudentDatabase where row = 'x'" );


    stmt.close();
    con.close();
   }
  catch(Exception e) {
  e.printStackTrace();
 }

Upvotes: 2

Views: 386

Answers (1)

SG_
SG_

Reputation: 496

stmt.executeUpdate("delete from StudentDatabase where row = 'x'" );

This SQL query is wrong. For example if you have following table in database, CustomerID CustomerName ContactName 1 Mike +248439533 2 Bob +345353535

and if you want to delete the row of "Mike" then you should write query as

delete from StudentDatabase where CustomerName = 'Mike'.

If you want to delete the row of CustomerID is "2", then you should write query as

delete from StudentDatabase where CustomerID = 2

In your case I hope this will your answer.

public class Test {
public static void main(String[] args) {
    int rowIndex = MyTable.getSelectedRow();
    String name = String.valueOf(MyTable.getValueAt(rowIndex, 1));

    try {
        Connection con;
        Statement stmt;


        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        con = DriverManager.getConnection("jdbc:ucanaccess://C://Users//abdul//Desktop/StudentDatabase.accdb");


        stmt = con.createStatement();

        int result = stmt.executeUpdate("delete from StudentDatabase where CustomerName = '"+name+"'" );

        if(result!=1){
            JOptionPane.showMessageDialog(null,"No record exists related to "+name);
        }



        stmt.close();
        con.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

}

Upvotes: 2

Related Questions