日期:2014-05-16 浏览次数:20501 次
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");
jdbcTemplate.update("INSERT INTO USER VALUES('" + user.getId() + "', '" + user.getName() + "', '" + user.getSex() + "', '" + user.getAge() + "')");
jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id}); 代码:jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.g etId(), user.getName(), user.getSex(), user.getAge()});
final String id = user.getId(); final String name = user.getName(); final String sex = user.getSex() + ""; final int age = user.getAge(); 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); } });
package org.springframework.jdbc.core; import java.sql.PreparedStatement; import java.sql.SQLException; public interface BatchPreparedStatementSetter { void setValues(PreparedStatement ps, int i) throws SQLException; int getBatchSize(); } ... public int[] insertUsers(final List users) { String sql = "INSERT INTO user (name,age) VALUES(?,?)"; BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() { public void setValues( PreparedStatement ps, int i) throws SQLException { User user = (User) users.get(i); ps.setString(1, user.getName()); ps.setInt(2, user.getAge().intValue()); } public int getBatchSize() { return users.size(); } }; return jdbcTemplate.batchUpdate(sql, setter); }
int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROMUSER");
String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?", new Object[] {id}, java.lang.String.class);
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); Returns an ArrayList (one entry for each row) of HashMaps (one entry for each column using the column name as the key)
List rows = jdbcTemplate.queryForList("SELECT * FROM USER"); Iterator it = rows.iterator(); while(it.hasNext()) { Map userMap = (Map) it.next(); System.out.print(userMap.get("user_id") + "\t"); System.out.print(userMap.get("name") + "\t"); System.out.print(userMap.get("sex") + "\t"); System.out.println(userMap.get("age") + "\t"); }