How to write Java code to delete data from a database?
To remove data from a database, you can use the DELETE command in SQL. Here is an example of deleting database data using Java code:
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteDataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库连接URL
String username = "root"; // 数据库用户名
String password = "password"; // 数据库密码
try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String sql = "DELETE FROM mytable WHERE id = 1"; // SQL语句,删除id为1的记录
int rowsAffected = statement.executeUpdate(sql); // 执行SQL语句并获取受影响的行数
System.out.println(rowsAffected + " 行记录已删除");
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Please make sure you have imported the correct JDBC driver and replace `url`, `username`, and `password` with your database connection information. Modify the value of the `sql` variable to fit your deletion requirements.