一、JDBC的工作过程
工作过程
1.1导入驱动
这里主要采用反射的方式,通过Class.forname方法。
1.2获取数据库链接对象
获取到comection的实例之后,搭建起程序与数据库的链接关系。
1.3获取Statement,执行sql语句
生成preparedstatement对象,执行sql语句。
二、创建过程
引入mysql-connector类库
将下载好的mysql-connector复制粘贴到项目文件中
![](https://img-blog.csdnimg.cn/img_convert/4110f0dd66a99714670e4b69a0d0e716.png)
右击选择 Build Path——Add to Build Path
![](https://img-blog.csdnimg.cn/img_convert/a9b14f7712d884773c4839d160cf1f4f.png)
创建好后,项目文件夹中会新增类库
![](https://img-blog.csdnimg.cn/img_convert/712454b5f4242822846d11fd8bfe6d6d.png)
创建JDBC工具类
![](https://img-blog.csdnimg.cn/img_convert/0ebfe3f0ebf43fee0c365d8f5e7fa0ed.png)
2.1添加工具类的属性
private String url = "jdbc:mysql://localhost:3306/topic?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
private String user = "root";//
private String passwd = "123";
private Connection c;
private PreparedStatement pst;
private ResultSet rs;
url对应的是数据库的位置
private String url = "jdbc:mysql://localhost:3306/topic?useUnicode=true&characte
2.2获取数据库链接对象
/**
* 获取数据库连接对象
* @return
* @throws Exception
*/
private Connection getConnect() throws Exception {
if((this.c == null)) {
Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动
this.c = DriverManager.getConnection(url, user, passwd);
}
return c;
}
2.3获取执行sql的preparedStatement对象
/**
* 获取执行sql的preparedStatement对象
* @param sql
* @return
* @throws Exception
*/
private PreparedStatement getPreparedStatement(String sql) throws Exception {
this.pst = getConnect().prepareStatement(sql);
return pst;
}
2.4更新数据库方法
protected int update(String sql) throws Exception{
int i = 0;
PreparedStatement pst = getPreparedStatement(sql);
i = pst.executeUpdate();
//this.closeAll();
return i;
}
2.5查询的方法
/**
* 查询的方法
* @param sql
* @return
* @throws Exception
*/
protected ResultSet find(String sql) throws Exception{
PreparedStatement pst = getPreparedStatement(sql);
rs = pst.executeQuery();
return rs;
}
2.6释放资源
/**
* 释放资源
*/
public void closeAll() {
try {
if(this.rs != null) {
this.rs.close();
}
if(this.pst != null){
this.pst.close();
}
if(this.c != null) {
this.c.close();
}
this.c = null;
}catch(Exception e) {
e.printStackTrace();
}
}