您的位置:首页 > 编程语言 > Java开发

Spring数据源Spring数据源配置之JDBC

2016-07-19 21:14 363 查看
1.配置applicationContext.xml文件

<!-- 配置数据库 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mytest3"></property>
<property name="username" value="root"></property>
<property name="password" value="1111"></property>
</bean>

<bean id="bookDao" class="com.hellojava.dao.BookDao">
<property name="dataSource" ref="dataSource"></property>
</bean>


2.业务层里面需要继承jdbcDaoSupport

1.> this.getJdbcTemplate().update(... ...)

2.> this.getJdbcTemplate().execute(... ...)

3.> this.getJdbcTemplate().query(... ...)

执行三者的区别:

update()只能数据表增删改操作

excute()可以执行任何SQL语句,甚至是create table...

query()用来执行查询操作
//比如关于修改采用两种方式
<span style="white-space:pre">	</span>//修改的第一种方法
//update()只能执行数据表增删改这样的操作
public int update(Book book){
String sql="update book set bookName=?,bookAuthor=?,bookPrice=?,bookInfo=? where bookId=?";
return this.getJdbcTemplate().update(sql, new PreparedStatementSetter(){
public void setValues(PreparedStatement psment) throws SQLException {
psment.setString(1, book.getBookName());
psment.setString(2, book.getBookAuthor());
psment.setDouble(3, book.getBookPrice());
psment.setString(4, book.getBookInfo());
psment.setInt(5, book.getBookId());
}
});
}
//修改的第二种方法
//execute()可以执行任何SQL语句,甚至是"create table..."
public int update1(Book book){
String sql="update book set bookName=?,bookAuthor=?,bookPrice=?,bookInfo=? where bookId=?";
return this.getJdbcTemplate().execute(sql, new PreparedStatementCallback<Integer>() {
public Integer doInPreparedStatement(PreparedStatement psment) throws SQLException, DataAccessException {
psment.setString(1, book.getBookName());
psment.setString(2, book.getBookAuthor());
psment.setDouble(3, book.getBookPrice());
psment.setString(4, book.getBookInfo());
psment.setInt(5, book.getBookId());
return psment.executeUpdate();
}
});
}

public Book loadById(int bookId){
Book book=new Book();
String sql="select * from book where bookId=?";
this.getJdbcTemplate().query(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psment=connection.prepareStatement(sql);
psment.setInt(1, bookId);
return psment;
}
}, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
book.setBookId(rs.getInt("bookId"));
book.setBookAuthor(rs.getString("bookAuthor"));
book.setBookName(rs.getString("bookName"));
book.setBookPrice(rs.getDouble("bookPrice"));
book.setBookInfo(rs.getString("bookInfo"));
}
});
return book;
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: