小学生学习Java的JDBC2

占位符 ?

public static void main(String[] args) throws ClassNotFoundException, SQLException {
           System.out.println("请输入");
           Scanner scanner = new Scanner(System.in);    
           String username1 = scanner.nextLine();
           String password1 = scanner.nextLine();
           Class.forName("com.mysql.jdbc.Driver");
           String url = "jdbc:mysql://localhost:3306/mydb2";
           String user = "root";
           String password = "123456";
           Connection connection = DriverManager.getConnection(url, user, password);
           // 获取预编译sql语句的对象
           // 使用占位符 问号?
           // 注意 使用?占位符 不用加单引号
           String sql = "select * from users where username=? and password=?";
           PreparedStatement statement = connection.prepareStatement(sql);
           // 设置占位符的值
           // 参数1 问号的索引 从1开始
           // 参数2 替换问号的值
           statement.setObject(1, username1);
           statement.setObject(2, password1);
           // 执行sql语句
           ResultSet resultSet = statement.executeQuery();
           while(resultSet.next()) {
                System.out.println(resultSet.getString("username") + resultSet.getString("password"));
           }
          connection.close();
          statement.close();
          resultSet.close();
    }

猜你喜欢

转载自blog.csdn.net/zmw1224/article/details/80697741