JdbcTemplate和druid的配置
阿新 • • 發佈:2020-09-11
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 test38() { 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; } }); } }