JDBC快乐指南
by cjq99419 详例可见buptmail中的Utils与DAOImpl
本指南只做快速的实践指导,具体细节原理忽略。
1. JDBC是啥?
Java DataBase Connectivity
简单来说,JDBC是sun提供的定义操作DB的接口,并由各个数据库厂商进行对应实现(如Mysql)
2. JDBC咋用?
-
导入jar包(add as library)
-
注册驱动
Class.forName("com.mysql.jdbc.Driver"); //mysql 5 Class.forName("com.mysql.cj.jdbc.Driver"); //mysql 8
mysql 5之后的版本可以不用注册驱动
-
获取连接对象
Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db", "root", "password"); // getConnection(String url, String username, String password);
url中的
localhost:3306
可以省略,即url = "jdbc:mysql:///db"
-
定义sql语句
String sql = "select * from user";
sql语句后不要带分号 ;
-
获取执行对象
Statement statement = connection.createStatement();
connection为3中的Connection对象
5 6 步顺序随意
-
执行sql
ResultSet result = statement.executeQuery(sql);
CRUD操作函数不同,返回不同,详见 JavaSE 8 API
-
释放资源
statement.close(); connection.close();
上述为传统JDBC使用方式,不推荐使用
3. 连接池
由上可知,执行sql语句需频繁的创建Connection对象以获取与本地或远程数据库的连接,因而在进行大量的数据操作时,创建Connection对象进行访问会极大的损耗性能。因而事先创建好存储多个Connection对象的容器,称其为连接池,以供用户进行使用,进而免去频繁的创建Connection对象。
目前主流JDBC连接池: C3P0, Druid(Ali)
提取Druid连接池工具类如下
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* JDBC工具类 使用Durid连接池
*/
public class JDBCUtils {
private static DataSource ds ;
static {
try {
//1.加载配置文件
Properties pro = new Properties();
//使用ClassLoader加载配置文件,获取字节输入流,可不在同级目录
InputStream is = JDBCUtils.class.getClassLoader().
getResourceAsStream("druid.properties");
pro.load(is);
//2.初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接Connection对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
druid.properties
#mysql8 需使用com.mysql.cj.jdbc.Driver
driverClassName=com.mysql.jdbc.Driver
#url格式同上,远程连接需写明ip
url=jdbc:mysql:///db
#填写用户名密码
username=root
password=password
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000
4. 所以到底咋写?
首先在DAO中创建JdbcTemplate对象,DateSource调用JDBCUtils静态方法作为初始参数。
可先简单了解一下 Jdbc Template
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
使用template进行CRUD操作。
-
select
需先了解容器与BeanPropertyRowMapper,会用也行
举个栗子:User为表user的JavaBean类,即类属性和表属性一一对应并提供对应getter,setter方法。
public List<User> findAll() { String sql = "select * from user"; List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; }
-
add delete update
同上,涉及sql安全注入问题。
public void add(User user) { String sql = "insert into user values(null, ?, ?, ?, ?)"; template.update(sql, user.getName(), user.getPassword(), user.getTel(), user.getEmail()); }
public void delete(int id) { String sql = "delete from user where id=?"; template.update(sql, id); }
public void update(User user) { String sql = "update user set name=?, password=?, tel=?, email=? where id=?"; template.update(sql, user.getName(), user.getPassword(), user.getTel(), user.getEmail(), user.getId()); }
-
sql安全注入
sql安全注入描述的是在使用拼接sql语句的时候会出现的安全问题
如下,通过用户名来查询用户数据:
StringBuffer sql = "select * from user where username=";
sql.append(user.input());
ResultSet result = statement.executeQuery(sql);
//上述程序通过id进行查询
此时可知,可知user.input()表示表单中用户添加内容,可通过网页限制等方式处理规定正则表达。
若没有规定格式,若用户输入cherry or 1=1,此时完整sql语句为:
"select * from user where username=cherry or 1=1"
此时可见,username=cherry无法对查询构成限制,进而导致用户可能通过这种方式获取到权限以外的数据。
因而,可以使用PreparedStatement解决这个问题。即用?代替输入的特定数据,并进行预编译,使用set方法对?值进行设置。由于上述文档直接使用Druid连接池和JDBCTemplate技术,封装了中间过程,因而可以直接使用JDBCTemplate对象实现预编译,依赖于DataSource。
综上所述,本套工具类使用Druid连接池简化Connection对象的创建调用,进而获取DataSource并使用JDBCTemplate简化Statement对应操作。
详细JDBCTemplate对应DML和DQL处理方式和输出格式可见 JavaSE 8 API