JdbcTemplate操作数据库
mentality_sx 人气:0JdbcTemplate操作数据库
准备工作
导入相关的jar包,建个数据库
在Spring配置文件中配置数据库连接池
<!-- 数据库连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="jdbc:mysql:///数据库名"></property> <property name="username" value="用户名"></property> <property name="password" value="密码"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean>
配置JdbcTemplate对象,注入dataSource
<!-- 创建JDBCtemplate对象,注入Datasource--> <bean id="jdbcTemplates" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- 注入dataSource--> <property name="dataSource" ref="dataSource"></property> </bean>
创建Service类,创建Dao类,在Dao中注入JdbcTemplate对象
具体操作
创建实体类Book.java,设置三个属性
package com.sun.Spring.Dao.entity; public class Book { private String userId; private String username; private String ustatus; public void setUserId(String userId) { this.userId = userId; } public void setUsername(String username) { this.username = username; public void setUstatus(String ustatus) { this.ustatus = ustatus; public String getUserId() { return userId; public String getUsername() { return username; public String getUstatus() { return ustatus; }
编写service和dao
(1)在dao进行数据库添加操作
(2)调用JdbcTemplate对象里update方法实现添加操作
BookDaoimpl.java
@Repository public class BookDaoImpl implements BookDao { // 注入JdbcTemplate @Autowired private JdbcTemplate jdbcTemplate; //添加的方法 @Override public void add(Book book) { // 创建sql语句 String sql="insert into t_book values(?,?,?)"; // 可变参数放在数组里面 Object[] args={book.getUserId(), book.getUsername(), book.getUstatus()}; // 调用方法实现,返回值是插入的记录数 int update = jdbcTemplate.update(sql, args); System.out.println(update); } }
BookService.java (调用add方法)
package com.sun.Spring.Dao.Service; import com.sun.Spring.Dao.Dao.BookDao; import com.sun.Spring.Dao.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService { // 注入Dao @Autowired private BookDao bookDao; // 添加的方法 public void addBook(Book book){ bookDao.add(book); } }
编写测试类进行测试即可
package com.sun.Spring.Dao.Test; import com.sun.Spring.Dao.Service.BookService; import com.sun.Spring.Dao.entity.Book; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJdbc { @Test public void Testupdate(){ ApplicationContext context= new ClassPathXmlApplicationContext("bean1.xml"); BookService bookService = context.getBean("bookService", BookService.class); Book book=new Book(); book.setUserId("1"); book.setUsername("Tom"); book.setUstatus("F"); bookService.addBook(book); } }
运行结果
加载全部内容