1.JDBC为什么会存在?
- 市面上有如此多的数据库厂商,Mysql、Oracle等等,他们使用不同的网络协议,Java开发人员为每一个数据库编写一套接口是不可能完成的,所以需要一个统一的接口。
- 从使用者来看,使用者不可能清楚每一个数据库的驱动程序。
2.JDBC的实现基于这样的思想:根据JDBC编写的程序能够与一个驱动管理器通信,驱动管理器通过驱动程序与实际的数据库进行通信。
3.如何使用JDBC与数据库连接?
使用mysql作为例子:(mysql-connection-java jar)
- DriverManager 驱动管理器
- 注册驱动:
- 为避免注册两次,使用Class.forName(“com.mysql.cj.jdbc.Driver”)
- 获取连接: DriverManager.getConnection(URI,root,password)
- 返回connection对象.
- 注册驱动:
- connection对象
- 创建执行sql语句的对象
- connection.prepareStatement() 返回preparedStatement对象
- 进行事务管理
- connection.setAutoCommit(true)
- connection.commit()手动提交
- connection.rollback()
- 创建执行sql语句的对象
- preparedStatement对象
- 执行sql语句
- preparedStatement.execute(sql) return boolean
- preparedStatement.executeQuery(sql) return ResultSet
- preparedStatement.executeUpdate(sql) return int
- 批处理
- addBatch(sql)
- executeBatch(sql)
- clearBatch(sql)
- 执行sql语句
4.代码演示:

使用jdbc查询id=1的name值
import java.sql.*;
public class JDBCTest1 {
public static void jdbctest(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/datatest?" +
"useEncoding=true&characterEncoding=utf-8&serverTimezone=UTC","root","123456"); //这里的连接符号是&,而在spring的配置文件中使用的是&
String sql="select * from student where id=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
ResultSet resultSet= preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("name"));
}
resultSet.close();
preparedStatement.close();// 别忘记释放资源
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JDBCTest1.jdbctest();
}
}
5.数据库连接池
- why? 一次访问就会创建一个连接,当同时访问的次数多了之后,创建连接这个动作一直在做,会极大的消耗数据库资源,造成内存溢出。
有了连接池之后,Dao层会去连接池中获得已经创建好的连接,不用再去新建连接,然后同数据库进行通讯。
- 使用c3p0连接池来连接数据库。共有三种方式来获得c3p0池支持的数据源,比较方便的是ComboPooledDataSource的实例。
- C3P0 的jar 包需要提前导入
public class C3P0Test {
public static void testC3p0() throws PropertyVetoException, SQLException {
//创建连接池对象
ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
//设置数据源
comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/datatest?useEncoding=true&characterEncoding=utf-8&serverTimezone=UTC");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("123456");
//获取连接
Connection connection=comboPooledDataSource.getConnection();
//sql语句
String sql="update student set name=? where id=?";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setString(1,"liuchen");
ps.setInt(2,1);
if(ps.executeUpdate()>0){
System.out.println("修改成功!");
}
}
public static void main(String[] args) throws PropertyVetoException, SQLException {
C3P0Test.testC3p0();
}
}

修改成功!