image.png
    image.png

    使用 mysql-connect-java 8

    1. Connection connection = null;
    2. Statement stmp = null;
    3. ResultSet rs = null;
    4. PreparedStatement preparedStatement = null;
    5. try {
    6. Class.forName("com.mysql.cj.jdbc.Driver");
    7. String url = "jdbc:mysql://localhost:33060/imooc?useSSL=false&userUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
    8. String username = "root";
    9. String password = "root";
    10. connection = DriverManager.getConnection(url, username, password);
    11. // 创建stmp 对象
    12. stmp = connection.createStatement();
    13. String sql = "select * from employee where dname=?";
    14. // 防止sql 注入
    15. preparedStatement = connection.prepareStatement(sql);
    16. preparedStatement.setString(1, pdname);
    17. // 结果集
    18. rs = preparedStatement.executeQuery();
    19. // rs.next() 返回布尔值 是否存在下一条, 有 返回true 提取下一条记录
    20. while (rs.next()) {
    21. Integer eno = rs.getInt(1); // JDBC 字段索引从1 开始
    22. String ename = rs.getString("ename");
    23. Float salary = rs.getFloat("salary");
    24. String dname = rs.getString("dname");
    25. System.out.println(eno + ename + salary + dname);
    26. }
    27. } catch (ClassNotFoundException e) {
    28. e.printStackTrace();
    29. } catch (SQLException e) {
    30. e.printStackTrace();
    31. } finally {
    32. try {
    33. if (rs != null) {
    34. rs.close();
    35. }
    36. } catch (Exception e) {
    37. }
    38. try {
    39. if (stmp != null) {
    40. stmp.close();
    41. }
    42. } catch (Exception e) {
    43. }
    44. try {
    45. if (connection != null && !connection.isClosed()) {
    46. connection.close();
    47. }
    48. } catch (Exception e) {
    49. }
    50. }