1、环境配置
1、安装MySQL
这里已安装简单跳过。
2、安装navicat
(Navicat是一套快速、可靠的 数据库管理 工具)
3、MySQL相关jar包安装
Java 连接 MySQL 需要驱动包,地址:mysql-connector-java-5.1.39-bin.jar 解压后得到 jar 库文件,然后在对应的项目中导入该库文件。
2、连接数据库
用navicat新建表输入数据
在idea新建项目导入库包
新建test文件输入以下代码
import java.sql.*;
public class test {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/123?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn= null;
Statement stmt = null;
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);;
try{
// 打开链接
System.out.println("连接数据库...");
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id,name, age FROM name";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 输出数据
System.out.print(", id: " + id);
System.out.print(", 姓名: " + name);
System.out.print(", 姓名: " +age);
System.out.print("\n");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
运行得到以下结论: