import java.sql.*; import java.util.Scanner;

public class JDBCExample {

public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    String user = "root";
    String password = "123456";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    
    try {
        //连接数据库
        conn = DriverManager.getConnection(url, user, password);
        
        //插入数据
        pstmt = conn.prepareStatement("INSERT INTO user(name, age, sex) VALUES(?, ?, ?)");
        pstmt.setString(1, "张三");
        pstmt.setInt(2, 20);
        pstmt.setString(3, "男");
        pstmt.executeUpdate();
        
        //修改数据
        pstmt = conn.prepareStatement("UPDATE user SET age = ? WHERE name = ?");
        pstmt.setInt(1, 21);
        pstmt.setString(2, "张三");
        pstmt.executeUpdate();
        
        //查询数据
        pstmt = conn.prepareStatement("SELECT * FROM user WHERE sex = ?");
        pstmt.setString(1, "男");
        rs = pstmt.executeQuery();
        while(rs.next()) {
            System.out.println(rs.getString("name") + " " + rs.getInt("age") + " " + rs.getString("sex"));
        }
        
        //删除数据
        pstmt = conn.prepareStatement("DELETE FROM user WHERE name = ?");
        pstmt.setString(1, "张三");
        pstmt.executeUpdate();
        
        //循环读取密码输入
        Scanner scanner = new Scanner(System.in);
        for(int i=0; i<3; i++) {
            System.out.println("请输入密码:");
            String passwordInput = scanner.next();
            if(passwordInput.equals("123456")) {
                System.out.println("恭喜你进入游戏");
                break;
            }
            if(i==2) {
                System.out.println("密码错误,结束游戏");
                System.exit(0);
            }
        }
        
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if(rs != null) rs.close();
            if(pstmt != null) pstmt.close();
            if(conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

Java JDBC 实例教程:数据库操作与密码验证

原文地址: https://www.cveoy.top/t/topic/n8XB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录