Truncate table using Java JDBC Example

We can make use of Statement or PreparedStatement to truncate a database table using Java JDBC,

Table: student:
mysql> select * from student;
| student_id | student_name |
|          1 | Sam          |
|          2 | Andy         |
2 rows in set (0.00 sec)
Java Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcExampleTruncateTable {

    public static void main(String[] args) throws SQLException {

        String url = "jdbc:mysql://localhost:3306/my_uat";
        String userName = "root";
        String password = "root123";
        String truncateTableQuery = "truncate table student";
        Connection connection = null;
        try {

            connection = DriverManager.getConnection(url, userName, password);
            Statement statement = connection.createStatement();
            System.out.println("Student table truncated!...");

        } catch (SQLException e) {
            System.out.println("Exception Occurred while truncating the table!");
        } finally {

Student table truncated!...

Truncate Table using Java JDBC Example

As you can see the table is now empty!

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.