第一种方式,重载PreparedStatementCreator
jdbcTemplate.update(
new
PreparedStatementCreator()
...
{
public PreparedStatement createPreparedStatement(Connection conn)...{
String sql="insert into user (name,age) values(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setInt(2,age);
return ps;
}
}
);
public PreparedStatement createPreparedStatement(Connection conn)...{
String sql="insert into user (name,age) values(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setInt(2,age);
return ps;
}
}
);
第二种方式,重载PreparedStatementSetter
jdbcTemplate.update(
"
insert into user(name,age) values(?,?)
"
,
new
PreparedStatementSetter()
...
{
public void setValues(PreparedStatement ps) throws SQLException ...{
ps.setString(1,name);
ps.setInt(2,age);
}
} );
// jdbcTemplate会自动创建PreparedStatementCreator实例,以提供传递给setValues方法的ps对象
public void setValues(PreparedStatement ps) throws SQLException ...{
ps.setString(1,name);
ps.setInt(2,age);
}
} );
// jdbcTemplate会自动创建PreparedStatementCreator实例,以提供传递给setValues方法的ps对象
第三种方式,直接使用SQL
jdbcTemplate.update("insert into user (name,age) "+"values (' " + name + " ', " +age +")");