日期:2014-05-16  浏览次数:20431 次

Spring2.5中JDBC连接数据库与JdbcTemplate的学习笔记
applicationContext.xml中的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans  default-autowire ="autodetect">
     <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:@localhost:1521:orcl</value>
          </property>
         <property name="username">
             <value>scott</value>
         </property>
         <property name="password">
             <value>tiger</value>
         </property>
     </bean>

</beans>
这个是具体连接数据库的java类 PersistenceFactory
package com.oztime.factory;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersistenceFactory {
private ApplicationContext tx;
//读取applicationContext.xml中的信息
public ApplicationContext getContext(){
tx=new ClassPathXmlApplicationContext("applicationContext.xml");
return tx;
}
//获取配置文件中的数据源
     public DataSource getDataSource(){
    DataSource datasource=null;
      datasource=(DataSource)this.getContext().getBean("dataSource");
      return datasource;
     }
     //连接数据库的方法
     public Connection makeConnection(){
    Connection conn=null;
    try {
conn=getDataSource().getConnection();
System.out.println(conn);
System.out.println("连接数据库成功!");
} catch (SQLException e) {
e.printStackTrace();
}
    return conn;
     }
     public Persistence getPersistence(DataSource dataSource){
Persistence persistence=new Persistence(dataSource);
persistence.setDataSource(dataSource);
return persistence;
}
}


下面是与数据库交互的java类 Persistenc
package com.oztime.factory;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
/*
*
* 与数据库交互的类
*/

public class Persistence {
private JdbcTemplate jdbcTemplate;
// private NamedParameterJdbcTemplate namedParameterJdbcTemplate = null;
private DataSource dataSource;
public Persistence(DataSource dataSource){
this.dataSource=dataSource;
this.jdbcTemplate=new JdbcTemplate(this.dataSource);
// this.namedParameterJdbcTemplate=new NamedParameterJdbcTemplate(this.jdbcT