Question

I have tables in MySQL and did make connection with this database from Eclipse. I can insert my information into my tables in my MySQL database, but I want the code that can help me for I delete some information from there.

I have this code for inserting but I need the code for deleting:

try {

    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    Connection connection = (Connection) DriverManager.
            getConnection("jdbc:mysql://localhost/fish", "root", "test");

    Statement s = (Statement) connection.createStatement();
    s.executeUpdate("insert into fish.store(tr_no,tr_day,tr_month,tr_year,age_type," +
            "class,pa_no,first_name,second_name,last_name,age,birth_place," +
            " tele_no,address,gender,booking_status) values" +
            "('" + fl_no + "','" + day + "','" + month + "','" + 
            year + "','" + age_type + "','" + fcl + "','" + spa + "'," +
            "'" + sfirst + "','" + ssecond + "','" + slast + "','" + sage + 
            "','" + sP_O_B + "','" + sphone + "'," +
            "'" + saddress + "','" + sgender + "','" + status + "')");


    Ticket t = new Ticket(sfirst, slast, ssecond, ifl, fcl, day2, month2, year2);
    t.setSize(830, 380);
    t.setVisible(true);
    t.setLocationRelativeTo(null);
    t.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    ImagePanel panel = new ImagePanel(new ImageIcon("2.jpg").getImage());
    t.getContentPane().add(panel);

} catch(SQLException ex) {
    Logger.getLogger(fish.class.getName()).log(Level.SEVERE, null, ex);
}
Was it helpful?

Solution

You can use something like this:

//initialize connection...
String deleteString = "DELETE FROM fish.store WHERE first_name = ? AND last_name = ?";
PreparedStatement deleteStmt = null;
try {
    //...
    deleteStmt =  connection.prepareStatement(deleteString);
    deleteStmt.setString(1, "Clint");
    deleteStmt.setString(2, "Eastwood");
    deleteStmt.executeUpdate();
    connection.commit();
} catch...
//close connection

Of course you have to replace the replacement of the statement with your own conditions (deleteStmt.set... (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)) and the WHERE clause of the SQL.

Have a look at http://dev.mysql.com/doc/refman/5.1/de/delete.html and http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top