If you are about to delete rows from a SQL Server database from Java you need a sane setup first. Install the JDBC driver for SQL Server and obtain a Connection from DriverManager or a DataSource. Keep credentials out of source code and use a connection pool for production. Nobody likes hunting phantom connections at two in the morning.
Do not trust user input. PreparedStatement prevents SQL injection and lets you bind parameters cleanly. A raw Statement can work for a quick experiment but it also works great for making embarrassing security headlines. PreparedStatement also helps with plan caching and cleaner logs.
try (Connection conn = dataSource.getConnection()) {
PreparedStatement ps = conn.prepareStatement("DELETE FROM Users WHERE id = ?")
ps.setInt(1, userId)
int affected = ps.executeUpdate()
if (affected == 0) {
// handle no row deleted
}
}
executeUpdate returns the number of rows changed. If it is zero then either the filter was wrong or you were trying to delete something that was already gone. Log enough context to debug the cause but do not log secrets or raw SQL with user values.
Wrap multi step deletes in a transaction to avoid half done messes. Turn off auto commit then commit when everything looks green. If anything throws you must rollback. Yes it is extra code but it beats handing a recovery task to your future self.
Connection conn = null
try {
conn = dataSource.getConnection()
conn.setAutoCommit(false)
PreparedStatement ps1 = conn.prepareStatement("DELETE FROM Orders WHERE userId = ?")
PreparedStatement ps2 = conn.prepareStatement("DELETE FROM Users WHERE id = ?")
// bind and execute both
conn.commit()
} catch (SQLException ex) {
if (conn != null) {
conn.rollback()
}
// log error without leaking private values
} finally {
if (conn != null) {
conn.close()
}
}
Use try with resources when possible so Java handles cleanup. Leaked connections cause mysterious production drama that nobody enjoys. Emit metrics for affected row count and failures so ops can pretend they were not surprised.
Deleting data is powerful and occasionally therapeutic. Do it with PreparedStatement and good Transaction Management and your Database Security will thank you. If not thank yourself for fewer late night firefights.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.