//首先,大家需要在大家的代码中引入mysql的驱动包 import java.sql.*; //然后,大家就可以开始连接数据库了 public class main { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&useUnicode=true&user=root&password=123456"); statement = connection.createStatement(); String sql = "select * from user"; resultSet = statement.executeQuery(sql); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String password = resultSet.getString("password"); System.out.println("id:" + id + ", name:" + name + ", password:" + password); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
代码中当中的路径就是连接mysql服务器的路径,根据自己电脑上的mysql安装路径进行更改。在成功连接数据库之后,大家就可以使用statement对象来执行查询命令,并利用resultSet对象来获取查询结果了。而finally语句块则是用来释放连接资源的,以免出现资源泄露的问题。