一、jdbc(Java DataBase Connectivity) java语言操控数据库。
JDBC本质:其实是官方定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
**/具体步骤
1、导入jar包
2、注册驱动
3、建立数据库连接对象 Connection
4、获取操作sql的对象Statement
5、执行sql语句,返回结果
6、处理结果
7、释放资源
**/具体代码实现
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
//导入jar包
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接对象
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","123");
//定义sql语句
String sql="select * from db";
//获取执行sql的对象
Statement statement=connection.createStatement();
//执行sql语句
ResultSet resultSet = statement.executeQuery(sql);
//处理结果
System.out.println(resultSet);
//释放资源
connection.close();
statement.close();
resultSet.close();
}
}
但是仅仅靠上边的代码来连接数据库,并操作数据显然是不够严谨的,因为他遇见异常只进行了抛出而且在释放资源时并没有进行检查是否为空,所以要进行修改。
**/具体代码
package cn.itcast.jdbc;
import java.sql.*;
public class JDBCDemo1 {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet =null;
//导入jar包
//注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//建立连接对象
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","123");
//定义sql语句
String sql="select * from db";
//获取执行sql的对象
statement=connection.createStatement();
//执行sql语句
resultSet = statement.executeQuery(sql);
//处理结果
System.out.println(resultSet);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//释放资源
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
再具体开发的时候我们不可能重复的进行注册驱动,建立连接的的操作因为代码太过繁琐也不方便后期的维护,这时就要用到JDBCUtils(JDBC工具类),抽取一个方法来完成注册驱动和链接,简单地说就是用一个类将注册驱动和连接数据库的操作封装起来,以后在操作数据库时就可以用这个类的对象来操作,这里还用到了配置文件,因此简化了代码。
**/具体代码
JDBCUtils
package cn.itcast.jdbcutils;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
Properties properties=new Properties();
//加载配置文件
try {
properties.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath()));
//获取配置文件的数据
url = properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
driver=properties.getProperty("driver");
//注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//方法重载 释放资源
public static void close(Statement statement,Connection connection){
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet resultSet,Statement statement,Connection connection){
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
调用JDBCUtils后的简化代码
package cn.itcast.jdbc;
import cn.itcast.jdbcutils.JDBCUtils;
import java.sql.*;
public class JDBCDemo1 {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet =null;
//导入jar包
//注册驱动
try {
connection = JDBCUtils.getConnection();
//定义sql语句
String sql="select * from db";
//获取执行sql的对象
statement=connection.createStatement();
//执行sql语句
resultSet = statement.executeQuery(sql);
//处理结果
System.out.println(resultSet);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(resultSet,statement,connection);
// if(resultSet!=null){
// try {
// resultSet.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
// if(statement!=null){
// try {
// resultSet.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
// if(connection!=null){
// try {
// resultSet.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
}
}
}
配置文件
url=jdbc:mysql://localhost:3306/db1
user=root
password=123
driver=com.mysql.jdbc.Driver
二、数据库连接池
常用的数据库连接池有两种
1. C3P0:数据库连接池技术
2. Druid:数据库连接池实现技术,由阿里巴巴提供的
这两种连接池都是通过标准接口:DataSource实现调用的
好处:
1. 节约资源
2. 用户访问高效
c3p0:数据库连接技术
1)导入jar包
2)定义配置文件,c3p0的配置文件有两种 c3p0.properties 或者 c3p0-config.xml,直接把他放在src文件夹下即可
配置文件如下:
<c3p0-config>
<!-- 使用默认的配置读取连接池对象 -->
<default-config>
<!-- 连接参数 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db</property>
<property name="user">root</property>
<property name="password">123</property>
<!-- 连接池参数 -->
<!--初始化申请的连接数量-->
<property name="initialPoolSize">5</property>
<!--最大的连接数量-->
<property name="maxPoolSize">10</property>
<!--超时时间-->
<property name="checkoutTimeout">3000</property>
</default-config>
</c3p0-config>
3) 创建核心对象 数据库连接池对象 ComboPooledDataSource
4)获取连接:getConnection
DataSource dataSource=new ComboPooledDataSource();
Connection conn = dataSource.getConnection();
Druid:数据库连接池实现技术
1)导入jar包
2)配置资源文件 资源文件格式为Druid.properties,可以放在任意文件夹下
配置文件:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db
username=root
password=123
#初始化链接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000
3)加载配置文件进内存
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
4)获取数据库连接池对象:通过工厂来获取 DruidDataSourceFactory
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
5)建立连接
Connection conn = ds.getConnection();
通过使用数据库连接池之后的JDBCUtiles工具类
package cn.itcast.jdbcutils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
public static DataSource dataSource=null;
static {
try {
//加载配置文件
Properties properties=new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取dataSource
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
public static void close(Statement statement,Connection connection){
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement statement , Connection connection, ResultSet resultSet){
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
三、Spring框架对JDBC的封装
Sping提供了一个JDBCTemplate对象简化JDBC的开发,这里要用到上边的JDBCUtiles工具类返回一个DataSource的对象,并把该对象传进JDBCTemplate方法中即可使用。
JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());
SpingJDBC提供了很多方法用于数据库的增删改查
update():执行DML语句。增、删、改语句
queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录
装为一个map集合
queryForList():查询结果将结果集封装为list集合(将每一条记录封装为一个Map集合,再将Map集合装载到List集合中)
query():查询结果,将结果封装为JavaBean对象 query的参数:RowMapper ,一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
**/new BeanPropertyRowMapper<类型>(类型.class)
queryForObject:查询结果,将结果封装为对象 一般用于聚合函数的查询。
**能力有限 如有错误请见谅