JavaWeb-JDBC
JDBC
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
连接
- 加载驱动
- 连接数据库 DriverManager
- 获得sql对象 Statement:CRUD
- 编写sql
- 返回结果集
- 释放连接
数据表
create table users(
id int PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
`email` VARCHAR(60),
`birthday` DATE
);
insert into users(id, `name`, `password`, `email`, `birthday`) values
(1, 'Bob', '123456', 'bob@qq.com', '2000-01-01'),
(2, 'Jack', '123456', 'jack@qq.com', '2000-01-01'),
(3, 'Tim', '123456', 'tim@qq.com', '2000-01-01');
程序
协议:子协议://主机:端口/数据库名?参数
jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8
package com.th0r.test;
import java.sql.*;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String pass = "123456";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//链接数据库
Connection connection = DriverManager.getConnection(url, user, pass);
//发送sql的对象
Statement statement = connection.createStatement();
String sql = "select * from users;";
//查询sql 返回为结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("name=" +resultSet.getString("name"));
}
//关闭连接池
resultSet.close();
statement.close();
connection.close();
}
}