在pom.xml的标签里加上下面的内容
如果是MySQL 5.8那么的版本号是5.x.x, 例如5.1.49
如果是MySQL 8.0那么的版本号是8.x.x, 例如 8.0.28
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
dependencies>
构建实体类, 类属性和表对应上, 方便来接收查询数据
对于一个学生信息表
CREATE TABLE student(
id BIGINT,
`name` VARCHAR(100),
sn BIGINT,
email VARCHAR(100),
classId BIGINT
)
新建学生类
public class Student {
private int id;
private String name;
private long sn;
private String email;
private int classId;
//记得自己加上toString()方法,和每个属性的getter和Setter方法
}
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.*;
import java.util.Scanner;
public class Demo01_Connection {
//先定义数据源对象, 待会用这个数据源操作数据库
//先定义一个名字, 待会再具体实现
private static DataSource dataSource = null;
//定义自己数据库的各种属性, 方便全局修改
// 数据库的用户名
private static final String USER = "root";
// 数据库的密码
private static final String PASSWORD = "123456";
// 数据库连接字符串(针对MySQL5) 本机数据库ip就是"localhost", 端口默认3306
private static final String URL = "jdbc:mysql://数据库服务ip:端口号/数据库名?characterEncoding=utf-8&useSSL=false";
// 如果是MySQL 8则是下面(mysql 8要加时区设置)
//private static final String URL = "jdbc:mysql://数据库服务ip:端口号/数据库名?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
public static void main(String[] args) {
// 1. 初化始数据源,待会赋给上面定义的数据源
MysqlDataSource myDataSource = new MysqlDataSource();
// 2. 设置连接的参数
myDataSource.setURL(URL);
myDataSource.setUser(USER);
myDataSource.setPassword(PASSWORD);
// 3. 把构建好的Mysql数据源赋值给JDBC中的datasource
dataSource = myDataSource;
//下面三个声明在try{}之外,方便finally也能识别
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
//通过数据源获取一个数据库连接
connection = dataSource.getConnection();
//接收用户输入的值
System.out.print("请输入姓名:");
Scanner scanner = new Scanner(System.in);
String sn = scanner.next();
//定义SQL语句
String sql = "select * from student where name = ?";
// 获取一个预处理对象
statement = connection.prepareStatement(sql);
// 处理占位符的值,要匹配上类型,参数1代表第几个占位符,后者表示要被替换的内容
statement.setString(1, sn);
// 4. 执行SQL
resultSet = statement.executeQuery();
if (resultSet.next()) { //如果读取到了内容
// 创建表示结果的JAVA对象
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setSn(resultSet.getLong(3));
student.setEmail(resultSet.getString(4));
student.setClassId(resultSet.getInt(5));
System.out.println(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
// 依次关闭资源,从后往前关
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.*;
public class DBUtil {
// 先定义一个数据源对象
private static DataSource dataSource = null;
// 数据库的用户名
private static final String USER = "root";
// 数据库的密码
private static final String PASSWORD = "123456";
// 数据库连接字符串
private static final String URL = "jdbc:mysql://127.0.0.1:3306/java78?characterEncoding=utf-8&useSSL=false";
static {
// 初始化数据源,类加载时运行
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(URL);
mysqlDataSource.setUser(USER);
mysqlDataSource.setPassword(PASSWORD);
dataSource = mysqlDataSource;
}
// 用private 修饰构造方法,使外部不能new 这个类的对象
private DBUtil() {}
//获取数据库连接
public static Connection getConnection () throws SQLException {
return dataSource.getConnection();
}
//关闭对象并释放资源
public static void close (ResultSet resultSet, PreparedStatement statement, Connection connection) {
// 依次关闭对象,并释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
省略了设置数据源参数和关闭数据源的操作
public class Main{
public static void main(String[] args) {
//声明三个对象
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1. 创建数据源并获取数据库连接
connection = DBUtil.getConnection();
// 2. 构造SQL语句
String sql = "select id, name, sn, email, classId from student order by id ASC";
// 使用SQL预处理对象处理SQL
statement = connection.prepareStatement(sql);
// 3. 执行SQL并获取结果,如果是结果集把结果集转成java对象
resultSet = statement.executeQuery();
// 遍历结果集,处理查询到数据
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setSn(resultSet.getLong(3));
student.setEmail(resultSet.getString(4));
student.setClassId(resultSet.getInt(5));
}
// 打印结果
System.out.println(student);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4. 释放资源
DBUtil.close(resultSet, statement, connection);
}
}
}
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Demo02_SelectAll {
public static void main(String[] args) {
// 查询到的所有学生信息放在List里
List<Student> students = null;
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1. 创建数据源并获取数据库连接
connection = DBUtil.getConnection();
// 2. 构造SQL语句
String sql = "select id, name, sn, email, classId from student order by id ASC";
// 使用SQL预处理对象处理SQL
statement = connection.prepareStatement(sql);
// 3. 执行SQL并获取结果,如果是结果集把结果集转成java对象
resultSet = statement.executeQuery();
// 遍历结果集,处理查询到数据
while (resultSet.next()) {
// 如果List为空则创建
if (students == null) {
students = new ArrayList<>();
}
// 解析结果集并封装成Student对象
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setSn(resultSet.getLong(3));
student.setEmail(resultSet.getString(4));
student.setClassId(resultSet.getInt(5));
// 加入到集合中
students.add(student);
}
// 打印结果
System.out.println(students);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4. 释放资源
DBUtil.close(resultSet, statement, connection);
}
}
}
如果你想update, 那么把SQL语句即可, 原理是相同的,基本不用改Java代码. 例如改成
Update student set age=10 where name=?
查询时statement.executeQuery(), 设置是statement.executeUpdate()
import java.sql.*;
import java.util.Scanner;
public class Demo03_Delete {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1. 获取数据库连接
connection = DBUtil.getConnection();
// 2. 构建SQL
String sql = "delete from student where name = ?";
// 接收用户的输入
System.out.print("请输入要删除的同学姓名:");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
// 3. 对SQL进行处理,并替换占位符
statement = connection.prepareStatement(sql);
//替换参数: 1代表第一个问号, name代表填入的数据
statement.setString(1, name);
// 4. 执行SQL并获取结果
int row = statement.executeUpdate();
if (row <= 0) {
System.out.println("删除失败.");
} else {
System.out.println("删除成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
DBUtil.close(null, statement, connection);
}
}
}
import java.sql.*;
import java.util.Scanner;
public class Demo04_Insert {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1. 获取数据库连接
connection = DBUtil.getConnection();
// 2. 构建SQL
String sql = "insert into student values (?, ?, ?, ?, ?)";
// 接收用户的输入
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要添加的同学Id:");
int id = scanner.nextInt();
// 姓名
System.out.print("请输入学生的姓名:");
String name = scanner.next();
// 学号
System.out.print("请输入学生的学号->");
long sn = scanner.nextLong();
// 邮箱
System.out.print("请输入学生的邮箱->");
String email = scanner.next();
// 班级编号
System.out.print("请输入学生的班级编号->");
int classId = scanner.nextInt();
// 3. 对SQL进行处理
statement = connection.prepareStatement(sql);
// 替换占位符
statement.setInt(1, id);
statement.setString(2, name);
statement.setLong(3, sn);
statement.setString(4, email);
statement.setInt(5, classId);
// 4. 执行SQL并获取结果
int row = statement.executeUpdate();
if (row <= 0) {
System.out.println("添加失败.");
} else {
System.out.println("添加成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
DBUtil.close(null, statement, connection);
}
}
}