JDBC入门

  1. 创建数据库
    1. create database web_test3;
    2. user web_test3;
    3. create table user(

id int primary key auto increment
username varchar(20),
password varchar(20) ,
nickname varchar(20);
age int
);
图片.png

  1. 引入jar包 配置 vscode
  2. JDBC的代码实现
  3. JDBC的开发步骤
    1. 第一步:加载驱动

Class.forName("com.mysql.jdbc.Driver");

  1. 第二步:获得链接

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web
_test3","root","abc")

  1. 第三步:基本操作

Statement statement = conn.createStatement();
String sql = "select * from user";
ResultSet rs =`` statement.executeQuery(sql);
循环遍历 while for while(rs.next()){};

  1. 第四步:获取资源

re.close();
statement.colse();
conn.close();

DriverManager驱动管理类

  1. 注册驱动
    • 如果需要注册驱动,使用DriverManager.registerDriver(new Driver());但是一般不会用
    • 实际开发中一般采用 Class.forName("com.mysql.jdbc.Driver");
  2. 获得链接
    • getConnection(url,user,password);

url 与数据库链接的路径 user 数据库用户名 password 数据库密码 主要关注的是url的写法
jdbc:mysql://localhost:3306/web_test3
jdbc :连接数据库协议
mysql:jdbc的子协议
localhost:连接的mysql数据库服务器主机地址 本机localhost 非本机填写IP地址
3306:mysql数据库服务器的端口号
web_test3:数据库名称
url连接本机 简写 jdbc:mysql

Connection

  1. connection:与数据库连接对象

    1. 创建执行sql语句的对象
    • 执行语句对象
      • Statement
      • CallableStatement
      • PreparedStatement
    1. 管理事务
      • setAutoCommit
      • commit
      • rollback

        Statement

  2. 执行SQL

  • execute
  • executeQuery
  • executeUpdate
    • 执行SQL方法
      • boolean execute(String sql);
        • 执行查询,修改,添加,删除
      • ResultSet execute(String sql);
        • 执行查询(select)
      • int executeUpdate(String sql);
        • 执行修改,添加,删除
  1. 执行批处理
  • addBatch
  • clearBatch
  • executeBatch

    ResultSet

    1. 结果集

  • ResultSet rs = statement.executeQuery(sql);

    JDBC配置信息提取

    1. 配置文件

    • 属性文件
      • 格式:扩展名是.properties
      • 内容:key = value
    • XML文件

      2. 提取信息到配置文件

    • 定义一个配置文件

    • key = value …

      3. 在工具类中解析属性文件

    • 获取到具体内容为常量赋值

    • Properties properties = new Porperties();
    • properties.load(new FileInputSteam("src/db.properties"));//获取properties文件
    • properties.getProperty("driverClassName);//获取driverClassName值

      JDBC的SQL注入漏洞

  1. 输入用户名 aaa’ — 密码 随机
  2. aaa’ or 1=1 密码随机

    JDBC注入漏洞解决

    1. 原因 存在SQL关键字 — or

    2. 解决

  • 需要采用PreparedStatement对象解决SQL注入漏洞。这个对象将SQL预先进行编译,使用?占位符。?所代表内容是SQL固定。再次传入变量(包含SQL的关键字)。这个时候也不会识别关键字

PreparedStatement pstmt = null;
pstmt = conn.prepareStatement(sql);//执行SQL
pstmt.setString(1,username); //设置第一个?占位符的值
pstmt.setString(2.password);//设置第二个?占位符的值
executeQuery();//获取结果

保存操作

  • 提交事务
  • 注意 除selcet 不用提交 其他都需要进行提交

int num = pstmt.executeUpdate();
if(num>0){
system.out.println("保存成功");
}
pstmt.commit();

  • 批处理

pstmt.addBatch(sql);//添加到批处理
pstmt.executeBatch();//执行批处理
pstmt.clearBatch;//清空批处理

JDBC事务管理 transaction

  1. 在转账中没有添加事务的管理,出现aaa账号钱转出丢失,账号bbb未收到转账

提交事务
setAutocommit 自动提交事务 //开始操作之前
commit 提交事务 //执行完操作进行提交
rollback 回滚事务 //出错回滚

连接池 自定义连接池

接口 DataSource

重写getconnection

Druid连接池使用

Druid的使用

  • 数据库连接之前 开始连接池 DruidDtadSource
  • conn = dataSource.getConnection();
  • 需手动连接数据库 dataSource.setDriverClassName(“com.mysql.jdbc.Driver”);…
  • 从属性文件中获取

Properties properties = new Properties();
properties.load(new FileInputStream("src/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSoucrce(properties);

  1. Properties properties = new Properties();
  2. properties.load(new FileInputStream("src/db.properties"));
  3. driverClassName = properties.getProperty("driverClassName");
  4. url = properties.getProperty("url");
  5. name = properties.getProperty("name");
  6. password = properties.getProperty("password");

druid.properties
#连接设置
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/stusys
username = root
password = root
#初始化连接
initialSize = 10
#最大空闲连接
maxIdle 20
#最小空闲连接
minIdle = 5
#超时等待时间以毫秒为单位6000毫秒/1000毫秒等于60秒
maxWait = 60000

  1. driverClassName=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/rubysiu
  3. name=root
  4. password=root

C3P0开源连接池

//获得链接:从连接池中获取
//创建连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource
//设置链接参数
dataSource.setDriverClass(“com.mysql.jdbc.Driver”);
其他参数…
//获取链接

C3P0采用文件配置

c3p0-config.xml 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <c3p0-config>
  3. <!-- 使用默认的配置读取连接池对象-->
  4. <default-config>
  5. <!-- 连接参数 -->
  6. <property name="drierClass">com.mysql.jdbc.Driver</property>
  7. <property name="jdbcUrl">jdbc:mysql://localhost:3306/stusys</property>
  8. <property name="user">root</property>
  9. <property name="password">root</property>
  10. <!-- 连接池参数 -->
  11. <!-- 初始连接数 -->
  12. <property name="initialPoolSize">5</property>
  13. <!-- 最大连接数 -->
  14. <property name="maxPoolSize">10</property>
  15. <!-- 最大等待时间 -->
  16. <property name="checkoutTimeout">2000</property>
  17. <!-- 最大空闲回收时间 -->
  18. <property name="maxIdleTime">1000</property>
  19. </default-config>
  20. </c3p0-config>

改写工具类

工具类代码实现

  1. /*
  2. * C3P0连接池
  3. */
  4. public class JunitSourceDemo {
  5. //创建一个连接池
  6. private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();
  7. //获得链接
  8. public static Connection getConnection() throws SQLException {
  9. return dataSource.getConnection();
  10. }
  11. //获得连接池
  12. public static DataSource getDataSource() {
  13. return dataSource;
  14. }
  15. //释放资源
  16. public static void release(Statement stmt,Connection conn) throws SQLException {
  17. stmt.close();
  18. conn.close();
  19. }
  20. public static void release(ResultSet rs,Statement stmt,Connection conn) throws SQLException {
  21. rs.close();
  22. stmt.close();
  23. conn.close();
  24. }
  25. }

DBUtlls

  • 对JDBC简单封装,而且没有影响性能。简化JDBC

    QueryRunner对象:核心运算类

    • 构造

QueryRunner
QueryRunner(dataSource ds);

  • 方法

Update 执行给定插入修改/
Query 知悉查询/

在一般情况下如果执行CRUD的操作
构造:
QueryRunner(DataSource ds);
方法:
int update(String sql,Object args);
T query(String sql,ResultSetHandler rsh,Object args);
如果有事务管理的话使用另一套完成CRUD的操作
构造:
QueryRunner();
方法:
int update(Connection conn,String sql,Object args);
T query(Connection conn,String sql,ResultSetHandler rsh,Object args);

  • 执行批处理

batch()

DBUtlls

方法:
设置事务 不自动提交
commitAndCloseQuietly();//提交事务
rollbackAndCloseQuietly();//处理异常

DBUtlls增删改

//创建核心类QueryRunner 注意抛出异常
QueryRunner queryRunner = new QuertyRunner(JDBCUtlls2.getDataSource);
queryRunner.update(sql,params);//insert 添加-delete 删除—update 修改

DBUtlls查询

  1. queryRunner.query()<br />//创建一个对象Account<br />`Account account = queryRunner.query("select * from account where id = ?",new ResultSetHandler<Account>(){`<br />`public Account handle(ResultSet rs) throws SQLException{`<br />`Account account = new Account();`<br />`if(rs.next()){`<br />`account.setId(rs.getInt("id"));`<br />`...`

``}
return account;

} ,1);
system.out.println(account)
})

ResultSetHandler的实现

ArrayHandler 和 ArrayListHandler

ArrayHandler 将一条记录封装到一个数组当中,这个数组应该是Object[]
ArraylistHandler 将多条记录封装到一个有Object[]的list集合中。
实现
QueryRunner queryRunner = new QuertyRunner(JDBCUtlls2.getDataSource);//获取连接
Object[] objs = queryRunner.query("select * from account where id = ?",new ArrarHandler(),1);//一条
List<Object[]> list =`` queryRunner.query("select * from account",new ArrarListHandler()); //多条

  1. public class DBUtilsDemo {
  2. @Test
  3. public void demo() throws SQLException{
  4. QueryRunner queryRunner = new QueryRunner(JunitSourceDemo.getDataSource());
  5. String sql ="select * from t_user ";
  6. List<Object[]> list = queryRunner.query(sql,new ArrayListHandler());
  7. for (Object[] objects : list) {
  8. System.out.println(Arrays.toString(objects));
  9. }
  10. }
  11. @Test
  12. public void demo1() throws SQLException{
  13. QueryRunner queryRunner = new QueryRunner(JunitSourceDemo.getDataSource());
  14. String sql ="select * from t_user where uid = ?";
  15. Object[] Objects= queryRunner.query(sql,new ArrayHandler(),1);
  16. System.err.println(Arrays.toString(Objects));
  17. }
  18. }

BeanHandler 和 BeanListHandler
BeanHandler 将一条记录封装到一个JavaBean中当中
BeanListHandler将多条记录封装到一个JavaBean的list集合中。 一条记录就是一个Java对象 将对各Java对象封装到一个List集合中;
QueryRunner queryRunner = new QuertyRunner(JDBCUtlls2.getDataSource);//获取连接
Account account = queryRunner.query("select * from account where id = ?",new BeanHandler<Account> (Account.class),1);//一条
List<Account[]> list =`` queryRunner.query("select * from account",new BeanListHandler<Account> (Account.class)); //多条

MapHandler 和MapListHandler
MapHandler 将一条记录封装到一个Map集合中 Map的key是列名 value就是表中列的记录
MapListHandler将多条记录封装到一个Map的list集合中
QueryRunner queryRunner = new QuertyRunner(JDBCUtlls2.getDataSource);//获取连接
Map<String,Object> map= queryRunner.query("select * from account where id = ?",new MapHandler(),1);//一条
List<Map<String,Object>> list =`` queryRunner.query("select * from account",new MapListHandler()); //多条

ColumnListHandler、ScalarHandler、KeyedHandler
ColumnListHandler 将数据中的某一列装到List中
ScalarHandler 将当个值进行封装 单值封装 返回long类型 count(*)
KeyedHandler(了解即可) 将一条记录封装到一个Map集合中,将多条记录封装到一个装有Map 的Map集合中。且外层的Map的Key是可以指定的