JDBC入门
- 创建数据库
- create database web_test3;
- user web_test3;
create table user(
id int primary key auto increment
username varchar(20),
password varchar(20) ,
nickname varchar(20);
age int
);
- 引入jar包 配置 vscode
- JDBC的代码实现
- JDBC的开发步骤
- 第一步:加载驱动
Class.forName("com.mysql.jdbc.Driver");
- 第二步:获得链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web
_test3","root","abc")
- 第三步:基本操作
Statement statement = conn.createStatement();
String sql = "select * from user";
ResultSet rs =`` statement.executeQuery(sql);
循环遍历 while for while(rs.next()){}
;
- 第四步:获取资源
re.close();
statement.colse();
conn.close();
DriverManager驱动管理类
- 注册驱动
- 如果需要注册驱动,使用
DriverManager.registerDriver(new Driver());
但是一般不会用 - 实际开发中一般采用
Class.forName("com.mysql.jdbc.Driver");
- 如果需要注册驱动,使用
- 获得链接
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
connection:与数据库连接对象
- 创建执行sql语句的对象
- 执行语句对象
- Statement
- CallableStatement
- PreparedStatement
执行SQL
- execute
- executeQuery
- executeUpdate
- 执行SQL方法
- boolean execute(String sql);
- 执行查询,修改,添加,删除
- ResultSet execute(String sql);
- 执行查询(select)
- int executeUpdate(String sql);
- 执行修改,添加,删除
- boolean execute(String sql);
- 执行SQL方法
- 执行批处理
- 需要采用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
- 在转账中没有添加事务的管理,出现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);
Properties properties = new Properties();
properties.load(new FileInputStream("src/db.properties"));
driverClassName = properties.getProperty("driverClassName");
url = properties.getProperty("url");
name = properties.getProperty("name");
password = properties.getProperty("password");
druid.properties#连接设置
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/stusys
username = root
password = root
#初始化连接initial
Size = 10
#最大空闲连接maxIdle 20
#最小空闲连接minIdle = 5
#超时等待时间以毫秒为单位6000毫秒/1000毫秒等于60秒maxWait = 60000
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/rubysiu
name=root
password=root
C3P0开源连接池
//获得链接:从连接池中获取
//创建连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource
//设置链接参数
dataSource.setDriverClass(“com.mysql.jdbc.Driver”);
其他参数…
//获取链接
C3P0采用文件配置
c3p0-config.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 使用默认的配置读取连接池对象-->
<default-config>
<!-- 连接参数 -->
<property name="drierClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/stusys</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 连接池参数 -->
<!-- 初始连接数 -->
<property name="initialPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">10</property>
<!-- 最大等待时间 -->
<property name="checkoutTimeout">2000</property>
<!-- 最大空闲回收时间 -->
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
改写工具类
工具类代码实现
/*
* C3P0连接池
*/
public class JunitSourceDemo {
//创建一个连接池
private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();
//获得链接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//获得连接池
public static DataSource getDataSource() {
return dataSource;
}
//释放资源
public static void release(Statement stmt,Connection conn) throws SQLException {
stmt.close();
conn.close();
}
public static void release(ResultSet rs,Statement stmt,Connection conn) throws SQLException {
rs.close();
stmt.close();
conn.close();
}
}
DBUtlls
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);
- 执行批处理
DBUtlls
方法:
设置事务 不自动提交
commitAndCloseQuietly();//提交事务
rollbackAndCloseQuietly();//处理异常
DBUtlls增删改
//创建核心类QueryRunner 注意抛出异常
QueryRunner queryRunner = new QuertyRunner(JDBCUtlls2.getDataSource);
queryRunner.update(sql,params);//insert 添加-delete 删除—update 修改
DBUtlls查询
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());
//多条
public class DBUtilsDemo {
@Test
public void demo() throws SQLException{
QueryRunner queryRunner = new QueryRunner(JunitSourceDemo.getDataSource());
String sql ="select * from t_user ";
List<Object[]> list = queryRunner.query(sql,new ArrayListHandler());
for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
}
}
@Test
public void demo1() throws SQLException{
QueryRunner queryRunner = new QueryRunner(JunitSourceDemo.getDataSource());
String sql ="select * from t_user where uid = ?";
Object[] Objects= queryRunner.query(sql,new ArrayHandler(),1);
System.err.println(Arrays.toString(Objects));
}
}
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是可以指定的