当前位置:网站首页>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这些。
查询总记录数(巨额):
边栏推荐
- 基于C语言实现的人机交互软件
- 23.5 event listeners of application events and listeners
- 2022年收益率最高的理财产品是哪个?
- Kotlin属性与字段
- node的js文件引入
- Espressif 玩转 编译环境
- C Entry series (31) -- operator overloading
- Does flinkcdc now support sqlserver instance name connection?
- 23.8 using the applicationrunner or commandlinerunner to implement applicationrunner and commandlinerunner
- C#入门系列(三十一) -- 运算符重载
猜你喜欢
[untitled]
Leetcode and query question summary
Poor English, Oracle OCP or MySQL OCP exam can also get a high score of 80 points
C#入门系列(三十一) -- 运算符重载
【数据库 】GBase 8a MPP Cluster V95 安装和卸载
Mysql8 dual master and dual slave +mycat2 read / write separation
[untitled]
Neo eco technology monthly | help developers play smart contracts
【加密周报】加密市场有所回温?寒冬仍未解冻 盘点上周加密市场发生的重大事件
Spark persistence strategy_ Cache optimization
随机推荐
Xshell batch send command to multiple sessions
正则表达式:判断是否符合USD格式
Mysql database connection / query index and other common syntax
Oracle 19C OCP 1z0-083 question bank (7-12)
Grid segmentation
Study notes of automatic control principle -- dynamic model of feedback control system
Oracle 19C OCP 1z0-082 certification examination question bank (24-29)
The full name of flitter IDFA is identity for advertisers, that is, advertising identifiers. It is used to mark users. At present, it is most widely used for advertising, personalized recommendation,
Which financial product has the highest yield in 2022?
Does flinkcdc now support sqlserver instance name connection?
Use index to optimize SQL query "suggestions collection"
Ansible important components (playbook)
[GUI] GUI programming; AWT package (interface properties, layout management, event monitoring)
Replication of SQL injection vulnerability in the foreground of Pan micro e-cology8
MySQL 8.0 OCP 1z0-908 certification examination question bank 1
2000年的教训。web3是否=第三次工业革命?
Number of briquettes & Birthday Candles & building blocks
Nodejs2day (modularization of nodejs, NPM download package, module loading mechanism)
P1825 [USACO11OPEN]Corn Maze S
Maximum common substring & regularity problem