JDBC(Java DataBase Connectivity)
java.sql* jar包 百度网盘下载
链接:https://pan.baidu.com/s/1FQpab9RpVkSNFGRVx8jGbQ
提取码:wsul
java连接数据库与关闭连接
Class.forName("com.mysql.jdbc.Driver");
// 连接MySQL服务器
String username = "root";
String password = "";
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/school?useUnicode=true&characterEncoding=UTF-8";Connection conn = DriverManager.getConnection(connectionUrl, username, password);
System.out.println("连接成功!");conn.close();
System.out.println("关闭连接!");
查询并获取数据
// 数据库查询, Statement语句 ResultSet结果集
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");// 如果有数据,rs.next()返回true
while (rs.next()) {
// 取出这一行记录
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone"); // 可能为null
Date birthday = rs.getDate("birthday");System.out.println(id + "\t" + name + "\t" + phone);
}