现在开发中有了mybatis、jdbcTemplate之后,已经很少公司会直接使用jdbc来连接数据库了,但是无论是mybatis还是jdbcTemplate,其底层都是jdbc。
这篇文章就主要介绍一下怎么通过jdbc来连接数据库。
在这之前,创建数据库jdbc,在数据库下创建user表
/*
Navicat Premium Data Transfer
Source Server : MaraDB
Source Server Type : MariaDB
Source Server Version : 100605 (10.6.5-MariaDB)
Source Host : 127.0.0.1:3306
Source Schema : jdbc
Target Server Type : MariaDB
Target Server Version : 100605 (10.6.5-MariaDB)
File Encoding : 65001
Date: 13/07/2023 18:36:09
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '12345' COMMENT '密码',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'mumu', '12345');
INSERT INTO `user` VALUES (2, 'system', '12345');
SET FOREIGN_KEY_CHECKS = 1;
jdbc连接数据库的步骤:
第一步:加载驱动
mysql8.0之前
Class.forName("com.mysql.jdbc.Driver");
mysql8.0之后
Class.forName("com.mysql.cj.jdbc.Driver");
第二步:获取数据库连接(通过DriverManager)
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = username;
Connection connection = DriverManager.getConnection(url, username, password);
第三步:获取PreparedStatement对象
String sql = "select username, password from user";
PreparedStatement statement = connection.prepareStatement(sql);
第四步:执行SQL,如果是查询类的语句,得到查询结果
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String username = resultSet.getString("username");
String password = resultSet.getString("password");
System.out.println("username = " + username);
System.out.println("password = " + password);
}
第五步:关闭数据库连接对象(建议写在finally语句块中)
完整的代码:
package com.example.jdbc;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.*;
@SpringBootTest
class JdbcTests {
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = username;
@Test
void testQuery() {
Connection connection = null;
String sql = "select username, password from user";
try {
connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String username = resultSet.getString("username");
String password = resultSet.getString("password");
System.out.println("username = " + username);
System.out.println("password = " + password);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Test
void testUpdate() {
Connection connection = null;
String sql = "update user set password = ? where username = ?";
try {
connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement(sql);
// 设置参数
statement.setString(1, "mhxy1218");
statement.setString(2, "mumu");
int updates = statement.executeUpdate();
System.out.println("本次修改共影响" + updates + "行记录。");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Test
void testInsert() {
Connection connection = null;
String sql = "insert into user(username, password) values (?, ?)";
try {
connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement(sql);
// 设置参数
statement.setString(1, "heyunlin");
statement.setString(2, "12345");
int updates = statement.executeUpdate();
System.out.println("本次共插入" + updates + "条记录。");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Test
void testDelete() {
Connection connection = null;
String sql = "delete from user where username= ?";
try {
connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement(sql);
// 设置参数
statement.setString(1, "heyunlin");
int updates = statement.executeUpdate();
System.out.println("本次共删除" + updates + "条记录。");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
PreparedStatement对象常用的方法有三个
- boolean execute():一般不用,返回的是sql语句执行的结果,如果执行成功返回true,否则返回false;
- int executeUpdate():用于执行DML语句,即insert/update/delete语句,返回受影响的行数;
- ResultSet executeQuery():用于执行查询类的sql,通过ResultSet对象获取查询结果,mybatis中帮我们自动从ResultSet获取查询的所有字段值,并封装成了我们定义的entity对象;
文章的代码已开源,可按需获取
jdbc连接mysqlhttps://gitee.com/he-yunlin/jdbc.git好了,文章就分享到这里了,如果这篇文章对你有所帮助,不要忘了点赞+收藏哦~