删除数据库中的行

时间:2016-08-21 07:10:05

标签: java database ms-access

我想从数据库中删除从JTable中选择的行我已检查过我的java程序是否已连接到数据库但我很困惑如何从ms access数据库中删除整行而不影响或触摸任何专栏只想删除jtable中选定的行

我的数据库包括8列全名,父姓,父亲,出生日期,班级,地址,城市和省

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();
 }

1 个答案:

答案 0 :(得分:3)

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

此SQL查询错误。例如,如果您在数据库中有以下表, CustomerID CustomerName ContactName 1 Mike +248439533 2 Bob +345353535

如果要删除“Mike”行,则应将查询写为

delete from StudentDatabase where CustomerName = 'Mike'

如果要删除CustomerID行为“2”,则应将查询写为

delete from StudentDatabase where CustomerID = 2

在你的情况下,我希望这是你的答案。

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();
    }
}

}