文章目录
1. 首先准备要测试的数据库
-- 创建用来测试 jdbc 的表
CREATE TABLE IF NOT EXISTS jdbcTest(
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '测试主键id',
`username` VARCHAR(30) NOT NULL COMMENT '用户名',
`password` VARCHAR(30) NOT NULL COMMENT '密码',
`email` VARCHAR(30) NOT NULL COMMENT '邮箱',
`birthday` DATE NOT NULL COMMENT '生日',
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
-- 添加几条测试数据
INSERT INTO `test`.`jdbctest`(`id`, `username`, `password`, `email`, `birthday`) VALUES
(1, '小明', '123456', '897161@126.com', '2000-02-09 21:15:55'),
(2, '小刚', '123456', '897161@126.com', '2000-02-09 21:15:55'),
(3, '小李', '123456', '897161@126.com', '2000-02-09 21:15:55')
2. 准备好 mysql-connector-java-5.1.47.jar 驱动
可以百度 Maven 仓库下载或去码云上下载我的仓库取其中的 jar 包
3. 创建一个普通的 java 项目,为其添加依赖
3.1 首先创建一个空项目
3.2 然后在该目录下创建 lib 文件夹,并将其 mysql 驱动放进去
3.3 将此 lib 文件夹添加到项目依赖中去
成功后的目录如下即可:
4. 编写测试代码操作 jdbc
package com.jdbc.test;
import java.sql.*;
/**
* 第一个 jdbc 测试案例
* @author: 南独酌酒 <211425401@126.com>
* @date: 2020/9/21 21:29
*/
public class JDBCTestDemo {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2. 提供数据库连接的信息和账号密码
/**
* useUnicode=true 支持中文编码
* characterEncoding=utf8 设置字符集的编码格式
* useSSL=true 使用安全的连接
*/
String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "123456";
//3. 连接数据库
connection = DriverManager.getConnection(url, username, password);
//4. 创建执行 sql 的对象
statement = connection.createStatement();
//5. 执行 SQL、获取返回结果并查看
String sql = "SELECT `id`,`username`,`password`,`email`,`birthday` FROM jdbcTest";
result = statement.executeQuery(sql);
while (result.next()) {
System.err.println("id=" + result.getInt("id"));
System.err.println("username=" + result.getString("username"));
System.err.println("password=" + result.getString("password"));
System.err.println("email=" + result.getString("email"));
System.err.println("birthday=" + result.getDate("birthday"));
System.err.println("======================");
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
//6. 释放连接
try {
result.close();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}