Help Save Code2care! 😢

I've lost 99% of my revenue to AdBlockers & AI. Your support could be the lifeline that keeps this passion project alive!

Buy Code2care a Coffee QR Code

Scan to Buy Me A Coffee and help me continue coding for you!

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();
            statement.executeUpdate(truncateTableQuery);
            System.out.println("Student table truncated!...");

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

Student table truncated!...

Truncate Table using Java JDBC Example

As you can see the table is now empty!

You can download this article in various formats for your convenience. Choose from the options below:

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has a Masters Degree in Computer Science with over 15+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright Code2care © 2024 | Privacy Policy | About Us | Contact Us | Search