JdbcTemplate和druid的配置
1.倒入jar包和配置的文件

driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test_db username=root password=88888888 initialSize=5 maxActive=10 maxWait=3000
所有的代码都是students的表运行的,这个是我的表的内容

2.创建students的class
public class Students {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.创建DBJCUntil的class
public class DBJCUntil {
private static DataSource dataSource = null;
static {
Properties properties = new Properties();
try {
properties.load(DBJCUntil.class.getClassLoader().getResourceAsStream("druid.properties"));
} catch (IOException e) {
e.printStackTrace();
}
try {
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
}
4.使用的代码
public class Main {
public static void main(String[] args) {
test4();
}
public static void test1() {
JdbcTemplate template = new JdbcTemplate(DBJCUntil.getDataSource());
String sqlStr = "update students set name=? where id = ?";
int resutl = template.update(sqlStr, "zhangwuji", 1);
System.out.println(resutl);
}
public static void test2() {
JdbcTemplate template = new JdbcTemplate(DBJCUntil.getDataSource());
String sqlStr = "select name from students where id = 1";
String name = template.queryForObject(sqlStr,String.class);
System.out.println(name);
}
public static void test3() {
String sql = "SELECT * FROM students where id = ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DBJCUntil.getDataSource());
Map<String, Object> map = jdbcTemplate.queryForMap(sql,1);
System.out.println(map);
}
public static void test4() {
JdbcTemplate template = new JdbcTemplate(DBJCUntil.getDataSource());
String sqlStr = "select * from students";
List<Students> list = template.query(sqlStr, new BeanPropertyRowMapper<>(Students.class));
for (Students model : list) {
System.out.println(model.getName() + " "+model.getAge());
}
}
public static void test5() {
JdbcTemplate template = new JdbcTemplate(DBJCUntil.getDataSource());
String sqlStr = "select * from students";
List<Students> list1 = template.query(sqlStr, new RowMapper<Students>() {
@Override
public Students mapRow(ResultSet resultSet, int i) throws SQLException {
Students students = new Students();
students.setName(resultSet.getString("name"));
System.out.println(i);
return students;
}
});
}
}
public static void test6() {
JdbcTemplate template = new JdbcTemplate(DBJCUntil.getDataSource());
String sqlStr = "select * from students where id = ? ";
Students students = template.queryForObject(sqlStr,new BeanPropertyRowMapper<Students>(Students.class),1);
System.out.println(students.getName());
}
浙公网安备 33010602011771号