jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, sex);
ps.setInt(4, age);
}
});
以上方法如果age是null如何处理
以上方法和写jdbcTemplate.execute("insert into...")有什么本质区别
直接拼接,会有注入问题。
还是利用PrepareStatement
[quote]以上方法如果age是null如何处理 [/quote]
两种情况:
1,如果数据库的age可以为null,则更新或者insert成功,数据库age为null。
2,如果数据库的age不可以为null,则更新或者插入失败,抛出异常DataAccessException ,并且插入或更新失败。
[quote]
以上方法和写jdbcTemplate.execute("insert into...")有什么本质区别 [/quote]
[b]有如下几点:[/b]
1,update背后是借助于java.sql.PreparedStatement完成,而execute是基于java.sql.Statement。([color=red]本质的区别在这里[/color])
2,update返回int, 即受影响的行数。execute返回void.
3,使用上有点不同,如:update可以带参数(指的是Object),而execute不可以。例如:
jdbcTemplate.update("update TableA set name = 'Andy’ where id=?", new Object[] {new Integer(3)});
jdbcTemplate.execute("update TableA set name = 'Andy’ where id=3");
更详细的使用看api:http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/jdbc/core/JdbcTemplate.html
要仔细看文档
[b]execute(String sql) 没有说是用Statement。[/b]
[quote]
public void execute(String sql)
throws DataAccessExceptionDescription copied from interface: JdbcOperations
Issue a single SQL execute, typically a DDL statement.
Specified by:
execute in interface JdbcOperations
Parameters:
sql - static SQL to execute
Throws: DataAccessException - if there is any problem[/quote]
[b]
但是从参数sql是一个static的语句,可以推测用Statement会比PrepareStatement好一点。(只是推测)。另外要清楚:
PrepareStatement 与 Statement 的接口的继承结构。[/b]
[code="java"]public interface PreparedStatement extends Statement[/code]
一个父接口,一个子接口。
所以,execute方法执行给定的 SQL 语句,可以是INSERT UPDATE SELECT等语句,该语句可能返回多个结果。在某些(不常见)情形下,单个 SQL 语句可能返回多个结果集合和/或更新计数。而Update只适合执行update语句,返回的就是更新行数的计数。
[color=blue][b]
一个通用的方法(execute),一个专用的方法(update),这应该是区别所在吧![/b][/color]
看看jdbcTemplate源码:
execute方法的源码如下:
[code="java"]public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
class ExecuteStatementCallback implements StatementCallback, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
public String getSql() {
return sql;
}
}
execute(new ExecuteStatementCallback());
}[/code]
sql注入问题的可选解决方法:sql语句最好不要拼凑,用参数。
[quote]看起来虽然更面向对象 [/quote]
主要的目的在于避免注入问题。