优秀代码案例
- preparedStatement的使用 (连接池由Druid产生)
public class Demo {
public static void main(String[] args) throws Exception {
// 配置文件方式
// 1 导入druid包
// 2 在src下有一个数据库的配置信息文件 此文件可以为任意名称
// 3 创建druid的连接 由derid的工厂生产出来的
Properties properties = new Properties();
// 目标:将src下druid.properties资源文件转换成流 jdK:类加载器
// 怎么获取到类加载 每个类的字节码文件对象有个方法可以获取类加载器
/*Class clazz=Demo.class;
ClassLoader classLoader = clazz.getClassLoader();
InputStream is = classLoader.getResourceAsStream("druid.properties");*/
// 将src指定资源转换成流
InputStream is = Demo.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
// 4 从druid中获取连接
Connection connection = ds.getConnection();
// 5 操作数据库
PreparedStatement preparedStatement = connection.prepareStatement("select * from user");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt("id");
System.out.println(id);
}
// 6 释放资源
JDBCUtils.closeZY(resultSet,preparedStatement,connection);
}
// jdbc的工具类
public class JDBCUtils {
private static DataSource dataSource=null;
static {
try {
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws Exception {
// 从连接池中获取连接
Connection connection = dataSource.getConnection();
return connection; // 来源于连接池
}
// 释放资源
public static void closeZY(ResultSet rs, Statement statement, Connection connection){
// 关闭resultSet
try {
if(rs!=null){
rs.close();
}
}catch (Exception e){
e.printStackTrace();
}
// 关闭statement
try {
if(statement!=null){
statement.close();
}
}catch (Exception e){
e.printStackTrace();
}
// 关闭connection
try {
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
2.动态代理
public class Demo {
public static void main(String[] args) {
User user = new User();
//user.save();
// 使用动态代理的方式对user对象的save进行前后的增强
// 11111 save... 2222
// 1 明确目标对象 user
// 2 目标对象有接口 Iuser
// 使用jdk的动态代理
// 参数1:和目标对象一样的类加载器
// 参数2:目标对象的接口 底层会实现和目标对象一样的接口 达到和目标对象有一样的方法
// 参数3:InvocationHandler的实现类 处理所有增强业务的
Iuser userProxy=(Iuser)Proxy.newProxyInstance(user.getClass().getClassLoader(),
new Class[]{Iuser.class},
new InvocationHandler() {
@Override //核心方法 增强的业务代码都要在这里面实现
// invoke:在代理对象调用任何方法都会执行
// 参数1 固定 代表代理对象引用
// 参数2 method:要增强的方法
// 参数3 args:要增强的方法方法在运行过程中需要的参数
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 就是对调用方法的业务增强
// 之前增强
System.out.println("aaaaa");
// 原方法执行
// 反射 1 本身应该调用这个方法的对象
Object value = method.invoke(user, args);
// 之后增强
System.out.println("bbbbb");
// invoke谁调用 返回给谁
return value;
}
});
// 代理对象调用方法
//11111 save.... 22222
//userProxy.save(); // 当代理对象调用任何方法 invoke方法都会执行 里面执行的是对调用方法(save)的业务增强
// aaaaa delete:abcd bbbbb
String value=userProxy.update("66666666666666666");
System.out.println(value);
}
}
// 接口
public interface Iuser {
public void save();
public void delete(String value);
public String update(String value);
}
public class User implements Iuser {
@Override
public void save() {
System.out.println("save...");
}
@Override
public void delete(String value) {
System.out.println("delete:"+value);
}
@Override
public String update(String value) {
System.out.println("update:"+value);
return "abcd/1234";
}
}
3.企业开发中使用 jdbcTemplate操作数据库的增删改 查
-
jdbcTemplate.execute(sql语句);
-
jdbcTemplate.update(); // 增删改
-
jdbcTemplate.queryForObject (String sql, Class
requiredType,Object…args)
单行单列的数据查询封装 -
jdbcTemplate.queryForMap (String sql,Object…args)
单行多列的数据查询封装 -
jdbcTemplate.queryForList(String sql,Object…args) list
-
jdbcTemplate.queryForObject(String sql,new
BeanPropertyRowMapper<>(类名.class),Object…args)
单行多列的数据查询封装 -
jdbcTemplate.query(String sql,new
BeanPropertyRowMapper<>(类名.class),Object…args)
多行多列的数据查询封装
// jdbcTemplate操作数据库的入门 ddl语句
public class Demo1 {
@Test //在db4数据库下创建一张product表(id pname price) execute() ddl语句
public void test1() throws Exception {
//1 导5个包
//2 创建核心对象 jdbcTemplate
// 会自动从传递的连接池中获取连接 创建语句执行着 会自动释放资源 归还连接
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
// 3 执行sql语句
jdbcTemplate.execute("CREATE TABLE product(id INT PRIMARY KEY AUTO_INCREMENT,pname VARCHAR(20),price DOUBLE)");
}
}
// jdbcTemplate操作数据库 dml语句
public class Demo2 {
/*
* update(String sql,Object..args) 增删改
* sql:要执行的sql语句
* args:可变参数 占位符要赋的值
*
* */
@Test //增
public void test1() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="insert into product values(?,?,?)";
int count = jdbcTemplate.update(sql, null, "小米手机2", 1000);
System.out.println(count);
}
@Test //删
public void test2() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="delete from product where id=?";
Object[] obj={2};
int count = jdbcTemplate.update(sql, obj);
System.out.println(count);
}
@Test //改
public void test3() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="update product set pname=? where id=?";
Object[] obj={"红米手机",1};
int count = jdbcTemplate.update(sql, obj);
System.out.println(count);
}
}
// jdbcTemplate操作数据库 dql语句
public class Demo3 {
@Test //单行单列的数据查询封装
//#方法: queryForObject(String sql, Class requiredType,Object...args)
// sql:要执行的sql语句
//requiredType:返回值的Class类型
//args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test1() throws Exception {
/*JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select count(*) from product";
int count = jdbcTemplate.queryForObject(sql, int.class);
System.out.println(count);*/
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());;
String sql="select pname from product";
String value = jdbcTemplate.queryForObject(sql, String.class);
System.out.println(value);
}
@Test //单行多列的数据查询封装
//方法:queryForMap(String sql,Object...args) map
// sql:要执行的sql语句
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test2() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product where id=?";
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 1);
System.out.println(map);
}
@Test //多行多列的数据查询封装
//方法:queryForList(String sql,Object...args) list<map>
// sql:要执行的sql语句
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test3() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
System.out.println(map);
}
}
@Test //单行多列的数据查询封装
//方法:queryForObject(String sql,new BeanPropertyRowMapper<>(类名.class),Object...args) 对象
// sql:要执行的sql语句
// BeanPropertyRowMapper:jdbctemplate提供的实现类,可以实现表字段和属性的映射 如果映射成立会就将表字段的值赋值给对象的属性
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test4() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product where id=?";
// 建议:表名和类名相同 字段名和属性名相同
Product product = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Product>(Product.class), 3);
System.out.println(product);
// 细节1:数据封装的时候和对象的属性无关,和set后面的属性有关
// 细节2:建议属性使用包装类型
}
@Test //多行多列的数据查询封装
//方法:query(String sql,new BeanPropertyRowMapper<>(类名.class),Object...args) 对象
// sql:要执行的sql语句
// BeanPropertyRowMapper:jdbctemplate提供的实现类,可以实现表字段和属性的映射 如果映射成立会就将表字段的值赋值给对象的属性
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test5(){
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
for (Product product : list) {
System.out.println(product);
}
}
}
@Test //单行多列的数据查询封装
//方法:queryForObject(String sql,new BeanPropertyRowMapper<>(类名.class),Object...args) 对象
// sql:要执行的sql语句
// BeanPropertyRowMapper:jdbctemplate提供的实现类,可以实现表字段和属性的映射 如果映射成立会就将表字段的值赋值给对象的属性
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test4() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product where id=?";
// 建议:表名和类名相同 字段名和属性名相同
Product product = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Product>(Product.class), 3);
System.out.println(product);
// 细节1:数据封装的时候和对象的属性无关,和set后面的属性有关
// 细节2:建议属性使用包装类型
}
@Test //多行多列的数据查询封装
//方法:query(String sql,new BeanPropertyRowMapper<>(类名.class),Object...args) 对象
// sql:要执行的sql语句
// BeanPropertyRowMapper:jdbctemplate提供的实现类,可以实现表字段和属性的映射 如果映射成立会就将表字段的值赋值给对象的属性
// args:sql语句占位符需要的可变参数 如果么有可以省略不写
public void test5(){
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
String sql="select * from product";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
for (Product product : list) {
System.out.println(product);
}
}
// jdbc的工具类
public class JDBCUtils {
private static DataSource dataSource=null;
static {
try {
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接池
public static DataSource getDataSource() {
// 获取连接池
return dataSource;
}
// 获取连接
public static Connection getConnection() throws Exception {
// 从连接池中获取连接
Connection connection = dataSource.getConnection();
return connection; // 来源于连接池
}
// 释放资源
public static void closeZY(ResultSet rs, Statement statement, Connection connection){
// 关闭resultSet
try {
if(rs!=null){
rs.close();
}
}catch (Exception e){
e.printStackTrace();
}
// 关闭statement
try {
if(statement!=null){
statement.close();
}
}catch (Exception e){
e.printStackTrace();
}
// 关闭connection
try {
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}