用Java操作MySQL目录
一、创建数据库
打开Navicat(我用的是DataGrip)的查询控制台
1、建库
sql代码:
create schema StudentManagement;
2、建表
sql代码:
建立教师表
create table teacher
(
t_id int not null primary key auto_increment,
t_name varchar(20) not null,
t_tel int,
t_username varchar(20) not null unique,
t_password varchar(20) not null
);
建立学生表
create table student
(
s_id int not null primary key auto_increment,
s_name varchar(20) not null,
s_sex varchar(20) not null check (s_sex in ('男','女')) default '未填写',
s_tel int,
s_className varchar(20)
);
二、开始准备jdbc
1、导入mysql驱动jar包
(1)进入Maven网站
(2)搜索框内搜索Java,点击第一个MySQL
(3)找到你要的那个版本号的jar包,点开它,下载它,我要的是8.20.16版本
(4)下载它
(5)把下载好的jar包文件复制粘贴放入你的Java项目内,我放在项目src的zpb.practice.libs文件夹下
(6)点击项目结构
(7)然后依次点击模块 -> 依赖 -> +(加号),弹出1 JAR 或目录…,点击它
(8)进入目录后点击你项目下jar包的位置,点击确定后MySQL驱动jar包即导入了你的项目中,再点击确认,就导入完成。
(9)成功后你的mysql-connector-java-8.0.16.jar包应该可以像我这样点开
2、开始写jdbc代码
(1)创建zpb.practice.db文件夹,在里面新建java类DBUtil
(2)在类里写入下面的代码
package zpb.practice.db;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 15:11
*/
public class DBUtil {
//连接信息
private static String driverName;
private static String url;
private static String username;
private static String password;
//注册驱动,使用静态块,只需注册一次
static {
//初始化连接信息
Properties properties = new Properties();
try {
properties.load(new FileReader("src/db.properties"));
driverName = properties.getProperty("driverName");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
//1、注册驱动
try {
//通过反射,注册驱动
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//jdbc对象
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
//获取连接
public void getConnection() {
try {
//2、建立连接
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
//更新操作:增删改
public int update(String sql, Object[] objs) {
int i = 0;
try {
getConnection();
//3、创建sql对象
preparedStatement = connection.prepareStatement(sql);
for (int j = 0; j < objs.length; j++) {
preparedStatement.setObject(j + 1, objs[j]);
}
//4、执行sql,返回改变的行数
i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
//查询操作
public ResultSet select(String sql, Object[] objs) {
try {
getConnection();
//3、创建sql对象
preparedStatement = connection.prepareStatement(sql);
for (int j = 0; j < objs.length; j++) {
preparedStatement.setObject(j + 1, objs[j]);
}
//4、执行sql,返回查询到的set集合
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
//断开连接
public void closeConnection() {
//5、断开连接
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
(3)创建jdbc的java属性文件,这里说明一下,本项目不仅仅是写一个粗糙的jdbc,而是写一个最好的jdbc,创立Java属性文件的好处在于我们将会把jdbc需要的路径,用户名,用户密码写在Java代码之外,一方面是很安全,一方面也方便了你的阅读和修改。
下面单击src,我们直接在src根目录下新建文件
文件名db.properties
,注意这里的文件后缀名为.properties,这种文件可以被Java的Properties类调用,db.properties内写入下面的代码
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/studentmanagement?serverTimezone=Asia/Shanghai
username=root
password=root
这里的四行,从上到下依次是驱动名,MySQL数据库的路径,MySQL用户名,MySQL用户密码。
三、那就运行吧
1、创建主线程,新建zpb.practice.main文件夹,在内创建main类,创建main方法,代码如下
package zpb.practice.main;
import zpb.practice.db.DBUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 16:02
*/
public class Main {
public static void main(String[] args) {
}
}
2、给数据库增加一条数据
package zpb.practice.main;
import zpb.practice.db.DBUtil;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 16:02
*/
public class Main {
public static void main(String[] args) {
DBUtil db = new DBUtil();
//更新操作(增加数据)
Object[] obj = {null, "乔布斯", "2243736958", "Apple", "root"};
int i = db.update("insert into teacher values(?,?,?,?,?)", obj);
System.out.println(i);
db.closeConnection();
}
}
3、查询一下是否添加成功
package zpb.practice.main;
import zpb.practice.db.DBUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 16:02
*/
public class Main {
public static void main(String[] args) {
DBUtil db = new DBUtil();
//更新操作(增加数据)
//Object[] obj = {null, "乔布斯", "2243736958", "Apple", "root"};
//int i = db.update("insert into teacher values(?,?,?,?,?)", obj);
//System.out.println(i);
//db.closeConnection();
//查询操作
Object[] objs = {};
ResultSet set = db.select("select * from teacher", objs);
try {
while (set.next()) {
int t_id = set.getInt("t_id");
String t_name = set.getString("t_name");
String t_tel = set.getString("t_tel");
String t_username = set.getString("t_username");
String t_password = set.getString("t_password");
System.out.println(t_id + " " + t_name + " " + t_tel + " " + t_username + " " + t_password);
}
} catch (SQLException e) {
e.printStackTrace();
}
db.closeConnection();
}
}
运行后,你的控制台内将显示你刚刚插入的那条数据(乔布斯)。
附:最终代码
DBUtil
package zpb.practice.db;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 15:11
*/
public class DBUtil {
//连接信息
private static String driverName;
private static String url;
private static String username;
private static String password;
//注册驱动,使用静态块,只需注册一次
static {
//初始化连接信息
Properties properties = new Properties();
try {
properties.load(new FileReader("src/db.properties"));
driverName = properties.getProperty("driverName");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
//1、注册驱动
try {
//通过反射,注册驱动
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//jdbc对象
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
//获取连接
public void getConnection() {
try {
//2、建立连接
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
//更新操作:增删改
public int update(String sql, Object[] objs) {
int i = 0;
try {
getConnection();
//3、创建sql对象
preparedStatement = connection.prepareStatement(sql);
for (int j = 0; j < objs.length; j++) {
preparedStatement.setObject(j + 1, objs[j]);
}
//4、执行sql,返回改变的行数
i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
//查询操作
public ResultSet select(String sql, Object[] objs) {
try {
getConnection();
//3、创建sql对象
preparedStatement = connection.prepareStatement(sql);
for (int j = 0; j < objs.length; j++) {
preparedStatement.setObject(j + 1, objs[j]);
}
//4、执行sql,返回查询到的set集合
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
//断开连接
public void closeConnection() {
//5、断开连接
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Main
package zpb.practice.main;
import zpb.practice.db.DBUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Peter Cheung
* @user PerCheung
* @date 2021/8/22 16:02
*/
public class Main {
public static void main(String[] args) {
DBUtil db = new DBUtil();
//更新操作(增加数据)
//Object[] obj = {null, "乔布斯", "2243736958", "Apple", "root"};
//int i = db.update("insert into teacher values(?,?,?,?,?)", obj);
//System.out.println(i);
//db.closeConnection();
//查询操作
Object[] objs = {};
ResultSet set = db.select("select * from teacher", objs);
try {
while (set.next()) {
int t_id = set.getInt("t_id");
String t_name = set.getString("t_name");
String t_tel = set.getString("t_tel");
String t_username = set.getString("t_username");
String t_password = set.getString("t_password");
System.out.println(t_id + " " + t_name + " " + t_tel + " " + t_username + " " + t_password);
}
} catch (SQLException e) {
e.printStackTrace();
}
db.closeConnection();
}
}
db.properties
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/studentmanagement?serverTimezone=Asia/Shanghai
username=root
password=root