搭建步骤
- 准备数据库
- 官网下载数据库连接驱动jar 包。https://downloads.mysql.com/archives/c-j/
- 创建 java 项目,在项目下创建 lib 文件夹,将下载的驱动 jar 包复制到文件夹里
- 选中 lib 文件夹右键 -> Add as Library,与项目集成
- 编写代码
代码实现
数据库
create database if not exists `atguigudb`;use atguigudb;create table t_emp (emp_id int auto_increment comment '员工编号' primary key,emp_name varchar(100) not null comment '员工姓名',emp_salary double(10, 5) not null comment '员工工资',emp_age int not null comment '员工年龄'
);insert into t_emp(emp_name, emp_salary, emp_age)
values ('andy', 777.77, 32),('大风哥', 666.66, 41),('康师傅', 111, 23),('Cavin', 123, 26),('小鱼儿', 123, 28);
java 代码
package com.atguigu.base;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCBase {public static void main(String[] args) throws Exception {Class.forName("com.mysql.cj.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/atguigudb";String username = "root";String password = "123456";Connection connection = DriverManager.getConnection(url, username, password);Statement statement = connection.createStatement();String sql = "select emp_id, emp_name, emp_salary, emp_age from t_emp";ResultSet resultSet = statement.executeQuery(sql);while (resultSet.next()) {int empId = resultSet.getInt("emp_id");String empName = resultSet.getString("emp_name");double empSalary = resultSet.getDouble("emp_salary");int empAge = resultSet.getInt("emp_age");System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);}resultSet.close();statement.close();connection.close();}
}