1、导入jdbcTemplate需要的jar包+数据库驱动jar包:
2、创建对象,设置数据库信息:
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///数据库名称");
dataSource.setUsername("用户名");
dataSource.setPassword("密码");
3、创建jdbcTemplate对象,设置数据源:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
4、调用jdbcTemplate对象的方法实现操作:
(1)添加
String sql = "insert into 表名称 values(?,?)";
jdbcTemplate.update(sql, "lucy", "250");
(2)修改
String sql = "update 表名称 set password=? where name=?";
jdbcTemplate.update(sql, "1314", "lucy");
(3)删除
String sql = "delete from 表名称 where name=?";
jdbcTemplate.update(sql, "lucy");
(4)查询——返回某个值
String sql = "select count(*) from 表名称";
jdbcTemplate.queryForObject(sql, Integer.class);
(5)查询——返回对象
//创建sql语句
String sql = "select * from user where name=?";
//第二个参数是接口RowMapper,需要自己写实现接口,自己做数据封装
User user = jdbcTemplate.queryForObject(sql, new MyRowMapper(), "lucy");
System.out.println(user);
System.out.println(user.getName()+user.getPassword());
在这个类外面
class MyRowMapper implements RowMapper<User>
{
@Override
public User mapRow(ResultSet rs, int num) throws SQLException
{
//1、从结果集里面把数据得到
String name = rs.getString("name");
String password = rs.getString("password");
//2、把得到数据封装到对象里面
User user = new User();
user.setName(name);
user.setPassword(password);
return user;
}
}
(6)查询——返回List集合
//创建sql语句
String sql = "select * from user";
//调用jdbcTemplate
List<User> list = jdbcTemplate.query(sql, new MyRowMapper());
ps:jdbc底层实现代码:
Connection conn = null;
java.sql.PreparedStatement psmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = (Connection) DriverManager.getConnection("jdbc:mysql:///spring","root","root");
//编写sql语句
String sql = "select * from user where name=?";
//预编译sql
psmt = conn.prepareStatement(sql);
//设置参数值
psmt.setString(1, "lucy");
//执行sql
rs = psmt.executeQuery();
//遍历结果集
while(rs.next())
{
String name = rs.getString("name");
String password = rs.getString("password");
System.out.println(name+password);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
rs.close();
psmt.close();
conn.close();
}
c3p0连接池底层实现代码:
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///数据库名称");
dataSource.setUser("root");
dataSource.setPassword("root");
c3p0连接池spring配置:
<bean id="" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>