1. 导入必要的包
import java.sql.*;
  1. 加载驱动程序
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
  1. 获得数据库连接
String url = "jdbc:mysql://xxx/yyy";  // xxx代表主机名,yyy代表数据库名
user = "xxx";                         // 自己的用户名
password = "xxx";                     // 自己的密码
Connection conn = DriverManager.getConnection(url, user, password);
  1. 创建Statement对象
Statement stmt = conn.createStatement();
  1. 对数据库进行增删改查,获取结果,这里以查询为例。若是对数据进行了修改,则要用executeUpdate()方法
String selectSql = "SELECT * FROM xxx WHERE xxx;";
ResultSet rs = stmt.executeQuery(selectSql);
// 操作ResultSet对象,获取结果
// ...
  1. 对数据库中的数据完成操作后,最后要关闭数据库连接。这里要按照结果集对象、Statement对象、连接对象的顺序进行依次关闭
try {
  if (rs != null) rs.close();
  if (stmt != null) stmt.close();
  if (conn != null) conn.close();
}
catch (Exception e) {
  e.printStackTrace();
}