Summary: this tutorial walks you through the steps of deleting data in a table from a Java program using JDBC.
To delete one or more rows of a database table from a Java program, you use the following steps:
- First, create a database connection to the SQLite database.
- Next, prepare the DELETE statement. In case you want the statement takes parameters, you use the question mark (?) placeholder inside the statement.
- Then, create a new instance of the
PreparedStatement
class by calling theprepareStatement()
method of theConnection
object. - After that, supply values in place of the question mark placeholder using the set* method of the
PreparedStatement
object e.g.,setInt()
,setString()
, etc. - Finally, execute the
DELETE
statement by calling theexecuteUpdate()
method of thePreparedStatement
object.
The following program deletes the row with id 3 in the warehouses
table of the test.db
database that we created in the creating table tutorial.
package net.sqlitetutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
*
* @author sqlitetutorial.net
*/
public class DeleteApp {
/**
* Connect to the test.db database
*
* @return the Connection object
*/
private Connection connect() {
// SQLite connection string
String url = "jdbc:sqlite:C://sqlite/db/test.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
/**
* Delete a warehouse specified by the id
*
* @param id
*/
public void delete(int id) {
String sql = "DELETE FROM warehouses WHERE id = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// set the corresponding param
pstmt.setInt(1, id);
// execute the delete statement
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
DeleteApp app = new DeleteApp();
// delete the row with id 3
app.delete(3);
}
}
Code language: Java (java)
First, you use the following SELECT statement TO check the warehouses
table before executing the delete program.
SELECT
id,
name,
capacity
FROM
warehouses;
Code language: SQL (Structured Query Language) (sql)
Second, run the DeleteApp
program.
Third, use the same SELECT
statement above to query data from the warehouses
table.
In this tutorial, you have learned how to delete data in the SQLite database from the Java program.
Was this tutorial helpful ?