Java连接MySQL数据库

x33g5p2x  于2021-10-06 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(534)

一、DBConnection 类

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. /** * @author: By yangbocsu * @date: 2021/10/6 10:10 * @description: 110.42.134.158:3306 "jdbc:mysql://110.42.134.158:3306/myemployees" */
  5. public class DBConnection {
  6. private static String driver = "com.mysql.jdbc.Driver";
  7. private static String URL = "jdbc:mysql://localhost:3306/myemployees?useSSL=true"; //myemployees:要连接的数据库名
  8. private static String USER = "root";
  9. private static String PASSWORD = "123";
  10. //?useSSL=true 不加它会产生的问题,如下
  11. // Wed Oct 06 11:20:14 CST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended.
  12. // According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
  13. // For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.
  14. // You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
  15. public static Connection getConnection()
  16. {
  17. Connection con = null;
  18. try
  19. {
  20. // DriverManager是类用来管理数据库中的所有驱动程序,调用它的静态方法可以getConnection(url,user,password)与数据库建立连接,
  21. // 连接成功会返回connection对象,后面的接口都会依赖于这个接口对象
  22. Class.forName(driver); //加载驱动程序
  23. con = DriverManager.getConnection(URL,USER,PASSWORD);
  24. System.out.println("已经连接上myemployees数据库");
  25. return con;
  26. }
  27. catch (ClassNotFoundException | SQLException e)
  28. {
  29. System.out.println("连接失败了!!!!");
  30. e.printStackTrace();
  31. }
  32. return null;
  33. }
  34. }

二、EmployeesMgr 类

  1. import java.sql.Connection;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. /** * @author: By yangbocsu * @date: 2021/10/6 10:27 * @description: */
  6. public class EmployeesMgr {
  7. public static void main(String[] args) throws SQLException {
  8. DBConnection dbc = new DBConnection();
  9. Connection con = dbc.getConnection();
  10. //向数据库发送SQL语句 需要创建 Statement类对象
  11. Statement stmt = con.createStatement();
  12. ResultSet res = stmt.executeQuery("select * from employees;");
  13. res.next();
  14. // while (res.next())
  15. {
  16. System.out.println(res.getString("email"));
  17. }
  18. con.close();
  19. }
  20. }

相关文章

最新文章

更多