Spring 连接 PostgreSQL

这个连接比刚才的那个稍微复杂了一点。

我新建了一个Java工程,

工程里面引用了Spring的包,

\spring-framework-3.0.6.RELEASE-with-docs\spring-framework-3.0.6.RELEASE\dist

目录下面的所有包,可能有些是不需要的,我没有耐心挑选了

由于使用数据源c3p0,所以引用了

\spring-framework-3.0.1.RELEASE-dependencies\com.mchange.c3p0\com.springsource.com.mchange.v2.c3p0\0.9.1.2\com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar

还引用了

\spring-framework-3.0.1.RELEASE-dependencies\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1\com.springsource.org.apache.commons.logging-1.1.1.jar

也不知道干嘛用的,不过不引用,好像会报错,没有仔细研究了。

当然了还要引用jdbc驱动

postgresql-9.1-901.jdbc4.jar

 

下面编写Java代码

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanTest {
public static void main(String[] args)
throws Exception
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
DataSource ds = ctx.getBean("dataSource",DataSource.class);
Connection conn = ds.getConnection();
Statement st = conn.createStatement();
ResultSet rt = st.executeQuery("select * from weather");
while(rt.next())
{
String test1=rt.getString(1);
System.out.println(test1);
}
rt.close();
st.close();
conn.close();
}

}

 

噢,对了,还忘了一个最重要的,spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-2.0.xsd"

default-lazy-init
="true">

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method
="close">
<property name="driverClass" value="org.postgresql.Driver"/>
<property name="jdbcUrl" value="jdbc:postgresql:testdb"/>
<property name="user" value="postgres"/>
<property name="password" value="nirvana7"/>
</bean>
</beans>

还有一个要注意的就是spring配置文件放置的位置,这个是跟java文件里面,引用配置文件的方法有关系的,

这里是用的是ClassPathXmlApplicationContext类,所以配置文件要放在这个工程bin目录下。

OK,可以运行了。



转载于:https://www.cnblogs.com/nirvana7/archive/2011/12/09/2282504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值