Statement的使用及其细节


DDL:
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入管理员的名字: ");
String admin_name = scanner.nextLine();
System.out.print("请输入管理员的密码: ");
String admin_pwd = scanner.nextLine();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "select name , pwd from admin where name =? and pwd = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, admin_name);
preparedStatement.setString(2, admin_pwd);
ResultSet resultSet = preparedStatement.executeQuery(sql);
if (resultSet.next()) {
System.out.println("恭喜, 登录成功");
} else {
System.out.println("对不起,登录失败");
}
DML:
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("请输删除管理员的名字: ");
String admin_name = scanner.nextLine();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "delete from admin where name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, admin_name);
int rows = preparedStatement.executeUpdate();
System.out.println(rows > 0 ? "执行成功" : "执行失败");
preparedStatement.close();
connection.close();
本文详细介绍了如何在Java中使用Scanner获取用户输入,通过Properties文件读取数据库配置,执行SQL语句进行管理员登录验证和删除操作。展示了PreparedStatement的使用技巧及错误处理。
574

被折叠的 条评论
为什么被折叠?



