JdbcTemplate以对象的方式操作数据库

来源:互联网 发布:网络骗局大全微信 编辑:程序博客网 时间:2024/06/01 07:23
1.创建接口和实现类
//PersonDao接口package com.entity;public interface PersonDao {public Person find(int id);}//PersonDao实现类PersonDaoImplpackage com.entity;import java.sql.*;import javax.sql.DataSource;public class PersonDaoImpl implements PersonDao {private DataSource dataSource;/** * 查找方法 */public Person find(int id) {Connection con=null;PreparedStatement ps=null;ResultSet rs=null;try{con=dataSource.getConnection();ps=con.prepareStatement("select * from person where id=?");ps.setInt(1, id);rs=ps.executeQuery();Person p=new Person();if(rs.next()){p.setId(rs.getInt("id"));p.setName(rs.getString("name"));p.setPassword(rs.getString("password"));}return p;}catch(SQLException e){e.printStackTrace();}finally{try {if(rs!=null){rs.close();} if(ps!=null){ps.close();}if(con!=null){con.close();}}catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}/** * Spring配置文件通过查找setDataSource方法,将数据源注入当前Bean中 * @param dataSource */public void setDataSource(DataSource dataSource) {this.dataSource = dataSource;}public DataSource getDataSource() {return dataSource;}}//编写测试类package com.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.entity.Hello;import com.entity.IHello;import com.entity.IHello2;import com.entity.IHelloHandler;import com.entity.Person;import com.entity.PersonDao;public class test1 {/** * @param args */public static void main(String[] args) {try {ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");PersonDao personDao=(PersonDao) context.getBean("personDao");Person p=personDao.find(1);System.out.println("姓名:"+p.getName()+",密码:"+p.getPassword());} catch (Throwable e) {// TODO Auto-generated catch blocke.printStackTrace();}}}



2.修改配置文件
<!-- 配置DataSource --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property><property name="url"><value>jdbc:oracle:thin:@192.168.1.32:1521:orcl</value></property><property name="username"><value>usera</value></property><property name="password"><value>usera</value></property></bean><bean id="personDao" class="com.entity.PersonDaoImpl"><property name="dataSource" ref="dataSource"></property></bean>

3.在数据库建立相应的表

4.运行结果
clipboard.png
0 0
原创粉丝点击