当前位置:网站首页>JDBC详解
JDBC详解
2022-04-23 14:05:00 【想到的名字都被人用了】
Driver 接口
Driver 接口的作用是来定义数据库驱动对象应该具备的一些能力。比如与数据库建立连
接的方法的定义所有支持 java 语言连接的数据库都实现了该接口,实现该接口的类我们称
之为数据库驱动类。在程序中要连接数据库,必须先通过 JDK 的反射机制加载数据库驱动
类,将其实例化。不同的数据库驱动类的类名有区别。
加载 MySql 驱动:Class.forName(“com.mysql.jdbc.Driver”);
加载 Oracle 驱动:Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager 类
DriverManager 通过实例化的数据库驱动对象,能够建立应用程序与数据库之间建立连
接。并返回 Connection 接口类型的数据库连接对象。
常用方法
- getConnection(String jdbcUrl, String user, String password)
该方法通过访问数据库的 url、用户以及密码,返回对应的数据库的 Connection 对象。 - JDBC URL:与数据库连接时,用来连接到指定数据库标识符。在 URL 中包括了该数据库的类型、
地址、端口、库名称等信息。不同品牌数据库的连接 URL 不同。
Connection
- Connection 接口:Connection 与数据库的连接(会话)对象。我们可以通过该对象执行 sql 语句并返回结
果。
连接 MySql 数据库:
Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");
连接 Oracle 数据库:
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");
连接 SqlServer 数据库:
Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port;
DatabaseName=database", "user", "password");
常用方法
- createStatement():创建向数据库发送 sql 的 Statement 接口类型的对象。
- preparedStatement(sql) :创建向数据库发送预编译 sql 的 PrepareSatement 接口类型的
对象。 - prepareCall(sql):创建执行存储过程的 CallableStatement 接口类型的对象。
- setAutoCommit(boolean autoCommit):设置事务是否自动提交。
- commit() :在链接上提交事务。
- rollback() :在此链接上回滚事务。
Statement 接口
用于执行静态 SQL 语句并返回它所生成结果的对象。
由 createStatement 创建,用于发送简单的 SQL 语句(不支持动态绑定)。
常用方法
- execute(String sql):执行参数中的 SQL,返回是否有结果集。
- executeQuery(String sql):运行 select 语句,返回 ResultSet 结果集。
- executeUpdate(String sql):运行 insert/update/delete 操作,返回更新的行数。
- addBatch(String sql) :把多条 sql 语句放到一个批处理中。
- executeBatch():向数据库发送一批 sql 语句执行。
PreparedStatement 接口
继承自 Statement 接口,由 preparedStatement 创建,用于发送含有一个或多个参数的 SQL
语句。PreparedStatement 对象比 Statement 对象的效率更高,并且可以防止 SQL 注入,所以
我们一般都使用 PreparedStatement。
常用方法
- addBatch()把当前 sql 语句加入到一个批处理中。
- execute() 执行当前 SQL,返回个 boolean 值
- executeUpdate()运行 insert/update/delete 操作,返回更新的行数。
- executeQuery() 执行当前的查询,返回一个结果集对象
- setDate(int parameterIndex, Date x)向当前SQL语句中的指定位置绑定一个java.sql.Date
值。 - setDouble(int parameterIndex, double x)向当前 SQL 语句中的指定位置绑定一个 double
值 - setFloat(int parameterIndex, float x)向当前 SQL 语句中的指定位置绑定一个 float 值
- setInt(int parameterIndex, int x)向当前 SQL 语句中的指定位置绑定一个 int 值
- setString(int parameterIndex, String x)向当前 SQL 语句中的指定位置绑定一个 String 值
- setObject(int parameterIndex,Object o) 常用,兼容几乎全部的实体类字段属性
ResultSet 接口
ResultSet 提供检索不同类型字段的方法。
常用方法
- getString(int index)、getString(String columnName)
获得在数据库里是 varchar、char 等类型的数据对象。 - getFloat(int index)、getFloat(String columnName)
获得在数据库里是 Float 类型的数据对象。 - getDate(int index)、getDate(String columnName)
获得在数据库里是 Date 类型的数据。 - getBoolean(int index)、getBoolean(String columnName)
获得在数据库里是 Boolean 类型的数据。 - getObject(int index)、getObject(String columnName)
获取在数据库里任意类型的数据。
ResultSet 对结果集进行滚动的方法
• next():移动到下一行。
• Previous():移动到前一行。
• absolute(int row):移动到指定行。
• beforeFirst():移动 resultSet 的最前面。
• afterLast() :移动到 resultSet
封装一个JDBC工具类
该工具类包含了connection连接池、,并将查询、修改等操作进行封装,并将resultSet映射成实体类,不需要用户区手动操作返回结果。
public class JDBCUtil {
private static final Integer SIZE = 30;
private static String driver;
private static String jdbcUrl;
private static String username;
private static String userpassword;
private static Queue<Connection> queue = null;
static {
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
driver = bundle.getString("driver");
jdbcUrl = bundle.getString("jdbcUrl");
username = bundle.getString("username");
userpassword = bundle.getString("userpassword");
try {
Class.forName(driver);
queue = new LinkedList<Connection>();
for(int i=0; i<SIZE;i++) {
Connection connection = DriverManager.getConnection(jdbcUrl, username, userpassword);
queue.add(connection);
}
} catch (ClassNotFoundException var2) {
var2.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static Connection getConnection(){
if(queue.size()!=0){
return queue.poll();
}
try {
return DriverManager.getConnection(jdbcUrl,username,userpassword);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
/**
* 封装查找api将查找到的结果封装为list集合返回给用户
* @param con
* @param sql
* @param parameters
* @param returnType
* @param <T>
* @return
*/
public static <T> List<T> queryList(Connection con, String sql, Object[] parameters, Class<T> returnType){
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
if(parameters!=null && parameters.length!=0) {
for (int i = 1; i <= parameters.length; i++) {
preparedStatement.setObject(i,parameters[i-1]);
}
}
ResultSet resultSet = preparedStatement.executeQuery();
List<T> list = mappingType(resultSet, returnType);
preparedStatement.close();
return list;
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static int executeUpdate(Connection connection,String sql,Object[] parameters){
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
if(parameters!=null && parameters.length!=0){
for (int i = 1; i <= parameters.length; i++) {
preparedStatement.setObject(i,parameters[i-1]);
}
}
int i = preparedStatement.executeUpdate();
preparedStatement.close();
return i;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return -1;
}
/**
* 将resultSet映射成实体类对象
* @param rs
* @param type
* @param <T>
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
private static <T> List<T> mappingType(ResultSet rs,Class<T> type) throws SQLException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
List<T> list = new ArrayList<T>();
Field[] fields = type.getDeclaredFields();
while(rs.next()){
T instance = type.newInstance();
for(Field field: fields){
String fieldName = field.getName();
field.setAccessible(true);
System.out.println("返回方法:set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
Method method = type.getMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), field.getType());
try {
method.invoke(instance, rs.getObject(fieldName));
}catch (SQLException e){
System.out.println("返回集没有该列");
}
}
list.add(instance);
}
return list;
}
public static void closeResource(Connection connection){
queue.add(connection);
}
public static void closeAll(){
for(Connection con:queue){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
版权声明
本文为[想到的名字都被人用了]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42861526/article/details/122172331
边栏推荐
- CDH cluster integration Phoenix based on CM management
- Wechat applet communicates with esp8266 based on UDP protocol
- Switch usage (wechat applet)
- centOS下mysql主从配置
- Wechat applet initializes Bluetooth, searches nearby Bluetooth devices and connects designated Bluetooth (I)
- 帆软报表设置单元格填报以及根据值的大小进行排名方法
- 收藏博客贴
- 多线程 @Async 线程池
- 帆软实现一个单选按钮,可以统一设置其他单选按钮的选择状态
- 分页SQL
猜你喜欢
帆软分割求解:一段字符串,只取其中某个字符(所需要的字段)
Easyexcel读取excel表地理位置数据,按中文拼音排序
1256:献给阿尔吉侬的花束
Quartus prime hardware experimental development (de2-115 board) experiment II function adjustable comprehensive timer design
趣谈网络协议
Taobao released the baby prompt "your consumer protection deposit is insufficient, and the expiration protection has been started"
修改ddt生成的测试用例名称
PySide2
poi操作word模板替换数据并且导出word
帆软实现一个单选按钮,可以统一设置其他单选按钮的选择状态
随机推荐
生产环境——
RobotFramework 之 用例执行
微信小程序进行蓝牙初始化、搜索附近蓝牙设备及连接指定蓝牙(一)
Easyexcel读取excel表地理位置数据,按中文拼音排序
L2-024 tribe (25 points)
Autumn recruitment in 2021, salary ranking No
smart-doc + torna生成接口文档
Restful WebService和gSoap WebService的本质区别
linux MySQL数据定时dump
Check in system based on ibeacons
Expression「Func「TSource, object」」 转Expression「Func「TSource, object」」[]
Pycharm连接远程服务器并实现远程调试
STM32 learning record 0007 - new project (based on register version)
服务器日志分析工具(识别,提取,合并,统计异常信息)
Nifi 快速安装及文件同步操作
Nacos+AspnetCore+Ocelot实战编码
微信小程序通过低功耗蓝牙设备进行定位及测距(二)
log4j 输出日志信息到文件中
DeepinV20安装Mariadb
MYSQL 主从同步避坑版教程