

使用 mysql-connect-java 8
Connection connection = null;Statement stmp = null;ResultSet rs = null;PreparedStatement preparedStatement = null;try {Class.forName("com.mysql.cj.jdbc.Driver");String url = "jdbc:mysql://localhost:33060/imooc?useSSL=false&userUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";String username = "root";String password = "root";connection = DriverManager.getConnection(url, username, password);// 创建stmp 对象stmp = connection.createStatement();String sql = "select * from employee where dname=?";// 防止sql 注入preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, pdname);// 结果集rs = preparedStatement.executeQuery();// rs.next() 返回布尔值 是否存在下一条, 有 返回true 提取下一条记录while (rs.next()) {Integer eno = rs.getInt(1); // JDBC 字段索引从1 开始String ename = rs.getString("ename");Float salary = rs.getFloat("salary");String dname = rs.getString("dname");System.out.println(eno + ename + salary + dname);}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {try {if (rs != null) {rs.close();}} catch (Exception e) {}try {if (stmp != null) {stmp.close();}} catch (Exception e) {}try {if (connection != null && !connection.isClosed()) {connection.close();}} catch (Exception e) {}}
