当前位置:网站首页>JDBC数据库连接池(Druid技术)
JDBC数据库连接池(Druid技术)
2022-07-26 08:41:00 【chy响当当】
目录
1.初识数据库连接池和Druid
(1)简介

(2)实现

标准接口DataSource(javax.sql下):


一般是由厂商来实现的
(3)使用步骤

jar包版本自己看呗
public static void main(String[] args) throws Exception {
//System.out.println(System.getProperty("user.dir"));
//1.导入
//2.定义配置文件
//3.加载配置文件
Properties pro = new Properties();
pro.load(new FileInputStream("src/druid.properties"));
//4.获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
//5.获取数据库连接 connection
Connection connection = dataSource.getConnection();
System.out.println(connection);
}PS:
//System.out.println(System.getProperty("user.dir")); load的地址要根据这一行的输出结果来填!!2.补充:数据库设计范式
数据库设计三大范式_xiaoyangcv的博客-CSDN博客_数据库设计三大范式
3.补充:数据库的备份和恢复
4.补充:JUnit和Scanner
Scanner:学会看API

自己去看吧
这个写的也不错: Scanner的各种用法_disgare的博客-CSDN博客_scanner用法
JUnit:

例子:

Before和After


5.补充:子查询回顾

PS:这些什么多行,单列指的是子查询的结果

6.Druid工具类

public class JDBCUtils { //1.定义成员变量 DataSource private static DataSource ds; static { try { //1.加载配置文件 Properties pro = new Properties(); //.class是字节码文件;getClassLoader()返回类的类加载器ClassLoader;getResourceAsStream(String name),返回用于读取指定资源的输入流Inputr。 //pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); pro.load(new FileInputStream("src/druid.properties")); //2.获取Datasource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //3.获取连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } //4.释放资源 public static void close(Statement stm, Connection con) throws SQLException { /* if (stm != null) { stm.close(); } if (con != null) { con.close(); }*/ close(null, stm, con); } //重载 public static void close(ResultSet rs, Statement stm, Connection con) throws SQLException { if (stm != null) { stm.close(); } if (con != null) { con.close(); } if (rs != null) { rs.close(); } } //5.获取连接池 public static DataSource getDataSource() { return ds; } }这就体现了数据封装和抽象的思想。
工具类测试
public static void main(String[] args) throws SQLException { Connection conn = null; PreparedStatement pstm = null; //添加操作,给dept添加一条记录 //获取连接: conn = JDBCUtils.getConnection(); //定义sql String sql = "INSERT INTO dept(id,dname,loc) VALUES (?,?,?)"; //获取pstm对象 pstm = conn.prepareStatement(sql); //给?赋值 pstm.setInt(1, 50); pstm.setString(2, "技术部"); pstm.setString(3, "南京"); //执行sql int i = pstm.executeUpdate(); System.out.println(i); //释放资源 JDBCUtils.close(pstm, conn); }结果:
7.JDBC Template(简单封装工具类)
(1)简介

(2)执行DML语句
//修改数据
public static void main(String[] args) {
//1.导入jar包
//2.创建JDBCTemplate对象
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//3.调用方法
//这里不需要申请连接,不需要释放资源,他内部有处理,我们只要关注sql语句
String sql="update emp set salary = 9000 where ename = ? ";
int i = template.update(sql, "孙悟空");
System.out.println(i);
}//插入
String sql2 = "insert into emp(id,ename,salary) values(?,?,?)"; int i1 = template.update(sql2, 1015, "周星驰", 10011);//为什么这里就要是双引号,因为上面那个句子双引号外面已经有了,而双引号只能嵌套单引号 System.out.println(i1);
//删除
String sql3="delete from emp where ename = ?"; int i2 = template.update(sql3, "孙悟空"); System.out.println(i2);
(3)执行DQL语句
map
public void test2(){ String sql="select * from emp where id = ?"; Map<String, Object> t1 = template.queryForMap(sql, 1002);//这里只能返回一条记录 System.out.println(t1); System.out.println(t1.values()); System.out.println(t1.get("id")); }查询结果集的长度只能是1
结果:
{id=1002, ename=卢俊义, job_id=3, mgr=1006, joindate=2001-02-20, salary=16000.00, bonus=3000.00, dept_id=30}
[1002, 卢俊义, 3, 1006, 2001-02-20, 16000.00, 3000.00, 30]
1002

list


JavaBean
注意一下rowmapperBeanPropertyRowMapper的实现过程_Qiuyuguohou的博客-CSDN博客_beanpropertyrowmapper
法一:自己写匿名内部类
String sql = "select * from emp"; List<Emp> query = template.query(sql, new RowMapper<Emp>() {//这个emp我们必须先自己写好 @Override public Emp mapRow(ResultSet resultSet, int i) throws SQLException { Emp emp = new Emp(); int id = resultSet.getInt("id"); String ename = resultSet.getString("ename"); String date = resultSet.getString("joindate"); double salary = resultSet.getDouble("salary"); emp.setId(id); emp.setSalary(salary); emp.setJoindate(date); emp.setEname(ename); return emp; } }); for (Emp emp : query) { System.out.println(emp.toString()); }缺点:没有简化我们的书写
法二:用它写好的几个接口:
@Test
public void test4() {
String sql = "select * from emp";
//这里只要传入泛型,然后指定字节码文件即可
List<Emp> emps = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : emps) {
System.out.println(emp);
}
}但是注意,这里面我们自己定义的Emp,里面如果有基本数据类型int、double,那么我们表里面要是有对应的null,就会报错,因为基本数据类型不接受Null,于是我们要改成引用更好,即封装类:Integer Double这些。
查询总记录数(巨额):

边栏推荐
- Solve the problem of C # calling form controls across threads
- One click deployment of lamp and LNMP scripts is worth having
- Winter vacation homework & Stamp cutting
- Redis advanced
- [freeswitch development practice] user defined module creation and use
- OA项目之我的会议(查询)
- Which financial product has the highest yield in 2022?
- 【搜索专题】看完必会的搜索问题之洪水覆盖
- 为什么要在时钟输出上预留电容的工位?
- Study notes of automatic control principle -- dynamic model of feedback control system
猜你喜欢
![[untitled]](/img/89/c3ab79eb325f0136114a568745924b.png)
[untitled]

Spark scheduling analysis

Cadence (x) wiring skills and precautions

Memory management - dynamic partition allocation simulation

Kotlin属性与字段

C Entry series (31) -- operator overloading

Write common API tools swagger and redoc

有限元学习知识点备案

Poor English, Oracle OCP or MySQL OCP exam can also get a high score of 80 points

利用模m的原根存在性判断以及求解
随机推荐
Use index to optimize SQL query "suggestions collection"
Oracle 19C OCP 1z0-082 certification examination question bank (30-35)
SSH,NFS,FTP
Neo eco technology monthly | help developers play smart contracts
Flutter upgrade 2.10
KV database based on raft consensus protocol
Transfer guide printing system based on C language design
12306 ticket system crawling - 1. Saving and reading of city code data
In the first year of L2, the upgrade of arbitrum nitro brought a more compatible and efficient development experience
Kept dual machine hot standby
内存管理-动态分区分配方式模拟
My meeting of OA project (query)
合工大苍穹战队视觉组培训Day6——传统视觉,图像处理
[abstract base class inheritance, DOM, event - learning summary]
【C语言】程序员筑基功法——《函数栈帧的创建与销毁》
Write common API tools swagger and redoc
Alphabetic string
OA项目之我的会议(查询)
基于C语言的内存管理-动态分区分配方式模拟
PXE principles and concepts

