JDBC的快速入门
JDBC概述
- JDBC为访问不同的数据库提供了统一,为使用者屏蔽了细节问题。
- Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
在Java程序使用数据库的时候,如果不同的数据库使用的方法不统一,不利于管理。所以就使用接口(Java厂商制定规范),规定一套接口规范,让不同的数据库厂商实现,在Java中统计调用接口的方法即可。
JDBC是Java提供一套用于数据库操作的接口API,Java程序员只需要面向这套接口编程即可。不同的数据库厂商,需要针对这套接口提供不同的实现。
JDBC程序编写步骤
-
注册驱动 - 加载Drive类。
Driver driver = new Driver();
-
获取连接 - 得到Connection。
String url = "jdbc:mysql://localhost:3306/database";
// jdbc:mysql://表示规定好的协议,通过JDBC的方式连接MySQL
//localhost 主机,也可以是IP地址,因为数据库在本机所以是localhost
//3306表示MySQL监听的端口
//database表示连接的是哪一个数据库
//MySQL的本质就是socket连接
//将用户名和密码放入到Properties 对象
Properties properties = new Properties();
//user 和password 是规定好的
properties.setProperty("user","root");//用户名
properties.setProperty("password","123");//密码
Connection connect = driver.connect(url, properties);
- 执行增删改查 - 发送sql 给MySQL执行。
String sql = "insert into website values('01','张三',18)";
- 释放资源 - 关闭相关连接。
statement.close();
connect.close();
JDBC快速入门
在数据库中建立一个表
CREATE TABLE website (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
age TINYINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
);
在idea中新建一个目录
将所需要的数据库连接文件放到里面去。
最后在把这个文件添加为库,加入到项目中,就可以使用JDBC了。
完整代码
package JDBC;
import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class jdbc01 {
public static void main(String[] args) throws SQLException {
//注册驱动
Driver driver = new Driver();//创建driver对象
//获取连接
String url = "jdbc:mysql://localhost:3306/database";
// jdbc:mysql://表示规定好的协议,通过JDBC的方式连接MySQL
//localhost 主机,也可以是IP地址,因为数据库在本机所以是localhost
//3306表示MySQL监听的端口
//database表示连接的是哪一个数据库
//MySQL的本质就是socket连接
//将用户名和密码放入到Properties 对象
Properties properties = new Properties();
//user 和password 是规定好的
properties.setProperty("user","root");//用户名
properties.setProperty("password","123");//密码
Connection connect = driver.connect(url, properties);
//connect相当于网络连接了
//执行sql
String sql = "insert into website values('01','张三',18)";
Statement statement = connect.createStatement();
//用于执行静态sql语句并放回生成的对象
int rows = statement.executeUpdate(sql);
//如果是 dml语句,放回的就是影响的行数
System.out.println(rows > 0 ? "成功" : "失败");
//释放资源
statement.close();
connect.close();
}
}
运行成功
当程序运行成功时,查询数据库,数据已经写入成功。
连接JDBC报错
Loading class
com.mysql.jdbc.Driver’. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
是下载的连接mysql的jar包版本太老,将老版本移除,在官网下载新版本就好。
并将导入的包从import com.mysql.jdbc.Driver;
改为import com.mysql.cj.jdbc.Driver;