使用该工具类需要从spring开发包中导入spring.jar和commons-logging.jar,这个模板是线程安全的。
JdbcTemplate:
public class JdbcTemplateTest {
static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
/**
* @param args
*/
public static void main(String[] args) {
User user = findUser("zhangsan");
// System.out.println("user:" + user);
// System.out.println("users:" + findUsers(3));
// System.out.println("user count:" + getUserCount());
// System.out.println("user name:" + getUserName(1));
System.out.println("data:" + getData(1));
}
static int addUser(final User user) {
jdbc.execute(new ConnectionCallback() {//想在插入的时候取主键,回调
public Object doInConnection(Connection con) throws SQLException, DataAccessException {
String sql = "insert into user(name,birthday, money) values (?,?,?) ";
PreparedStatement ps = con.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
ps.setFloat(3, user.getMoney());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next())
user.setId(rs.getInt(1));
return null;
}
});
return 0;
}
static Map getData(int id) {
String sql = "select id as userId, name, money, birthday from user where );
prop.load(is);
myDataSource = BasicDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static DataSource getDataSource() {
return myDataSource;
}
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(url, user, password);
return myDataSource.getConnection();
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
// myDataSource.free(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}