大部分人刚开始学Java的时候,都是使用Jdbc连接数据库,其实Jdbc已经能够满足我们大部分的基础需求,但是使用Jdbc有一点不好,就是麻烦,必须创建大量的冗余代码,必须自己来管理数据库资源,比如创建连接,关闭连接,处理异常,获取PreparedStatement,设置SQL语句参数等等,虽然操作简单,但是效率着实不高。
所以,新入职的同事在做一个demo的时候,我就强烈地推荐他使用JdbcTemplate,使用JdbcTemplate可节省大量的冗余代码,让使用者只需关注业务逻辑即可。
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* 提供连接
*/
public class DruidUtils {
private static DataSource dataSource = null;
static { // 必须优先执行 只执行一次
try {
// 需要一个文件流
InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
// 创建配置文件对象
Properties props = new Properties();
props.load(is);
// 核心类
dataSource = DruidDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回数据源方法
*
* @return
*/
public static DataSource getDataSource() {
return dataSource;
}
/**
* 提供连接的方法
*
* @return
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
// 使用示例
JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
String sql = "SELECT MAX(qi_hao) FROM " + dataTableName;
Object max = template.queryForObject(sql, String.class);
maxQiHao = String.valueOf(max);
你看,只要把连接封装为DruidUtils公共方法,增删改查用起来就相当地简单,那么,JdbcTemplate的一些常用方法有哪些呢?JdbcTemplate主要提供:
1)execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
void execute(DDL的SQL语句);//数据库表的创建
JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
template.execute(
"CREATE TABLE user (id int(11) NOT NULL AUTO_INCREMENT,username varchar(50) DEFAULT NULL,PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8");
2)update方法及batchUpdate方法:
update方法用于执行新增、修改、删除等语句;
batchUpdate方法用于执行批处理相关语句;
JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
String hql = "UPDATE user SET username='张三' WHERE username='李四'";
int aa = template.update(hql);
/**
* 注:使用批量更新需根据具体情况选择不同参数
*/
int[] cc = template.batchUpdate("UPDATE user SET username='张三' WHERE username=?", "李四");
3)query方法及queryForXXX方法:用于执行查询相关语句;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.xf.jc.util.DruidUtils;
public class Test {
public static void main(String[] args) {
JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
/**
* 查询单个字段值
*/
String s = template.queryForObject("select username from user where id=?", String.class, 3);
Integer s2 = template.queryForObject("select id from user where id=?", Integer.class, 4);
/**
* 使用queryForObject方法和BeanPropertyRowMapper做映射还可以查询一个具体类对象
*/
User user = template.queryForObject("select * from user where id=?",
new BeanPropertyRowMapper<User>(User.class), 3);
/**
* 查询单条记录
*/
Map<String, Object> map = template.queryForMap("SELECT * FROM user WHERE id=?", 3);
/**
* 查询多条记录
*/
List<Map<String, Object>> maps = template.queryForList("SELECT * FROM user");
/**
* 查询多条记录用RowMapper做映射成对象
*/
List<User> query = template.query("select * from user where id in(?,?)", new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
int id = resultSet.getInt("id");
String username = resultSet.getString("uname");
User user = new User(id, username);
return user;
}
}, 3, 4);
/**
* 查询多条记录用BeanPropertyRowMapper做映射成对象
*/
List<User> use = template.query("select * from user where id in(?,?)",
new BeanPropertyRowMapper<User>(User.class), 3, 4);
}
}
4)call方法:用于执行存储过程、函数相关语句。