create database spring_day;
use spring_day;
create table t_user(
id int primary key auto_increment,
username varchar(50),
password varchar(32)
);
insert into t_user(username,password) values('jack','1234');
insert into t_user(username,password) values('rose','5678');
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jdbcTemplate.execute("create table t_user(+ "+
" id int primary key auto_increment," +
" username varchar(50)," +
"password varchar(32)");
System.out.println("账户表 t_user 创建成功");
public class User {
private Integer id;
private String username;
private String password;
public static void main(String[] args) {
// 1 创建数据源 (连接池) dbcp
BasicDataSource dataSource = new BasicDataSource();
// * 基本 4 项
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring_day");
dataSource.setUsername("root");
dataSource.setPassword("123456");
// 2 创建模板
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
// 3 通过 api 操作
jdbcTemplate.update("insert into t_user(username,password) values(?,?);", "tom" , "998");
}
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void updata(User user) {
String sql = "updata t_user set username=?, password=? where id =?";
Object[] args = {user.getUsername(),user.getPassword(),user.getId()};
jdbcTemplate.update(sql,args);
}
@Test
public void demo02 () {
User user = new User();
user.setId(1);
user.setUsername("接客");
user.setPassword("998");
String xmlPath = "com/c_dbcp/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserDao userDao = (UserDao) applicationContext.getBean("UserDaoId");
userDao.updata(user);
}
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void updata(User user) {
String sql = "update t_user set username=?, password=? where id =?";
Object[] args = {user.getUsername(),user.getPassword(),user.getId()};
jdbcTemplate.update(sql,args);
}
// 查询所有
public List findAll() {
return jdbcTemplate.query("select * from t_user",new Object[]{}, new BeanPropertyRowMapper(User.class));
}
}
public class TestC3P0 {
@Test
public void demo02 () {
User user = new User();
user.setId(1);
user.setUsername("接客");
user.setPassword("999");
String xmlPath = "com/d_c3p0/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserDao userDao = (UserDao) applicationContext.getBean("UserDaoId");
userDao.updata(user);
List allUser = userDao.findAll();
for (User user : allUser) {
System.out.println(user);
}
}
}
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring_day
jdbc.user=root
jdbc.password=123456