Spring 连接Oracle数据库 例子

Spring连接数据库,

spring用的配置文件

设定数据库连接方式。。。

工程结构如下图:

qq%e6%88%aa%e5%9b%be20161122135358

最终执行结果:

qq%e6%88%aa%e5%9b%be20161122135532

HelloWorldTest.java

package spring.test;

import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class HelloWorldTest {
public static void main(String[] args) throws SQLException {
ApplicationContext context = new FileSystemXmlApplicationContext(“SpringTest.xml”);

SpringBean bean = (SpringBean) context.getBean(“helloWorld”);
bean.show();
}
}

SpringBean.java

package spring.test;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class SpringBean {

@Autowired
private JdbcTemplate jdbcTemplate;

public void show(){

String sql1 = “select * from I_USER”;
List<Map<String, Object>> ret = jdbcTemplate.queryForList(sql1);
for (Map<String, Object> map : ret) {
System.out.println(map.get(“ID”).toString() + “-” + map.get(“NAME”).toString());
}
}
}

SpringTest.xml

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd”>

<bean id=”helloWorld” class=”spring.test.SpringBean”>
</bean>
<context:component-scan base-package=”spring.test” />

<bean id=”dataSource”
class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=”driverClassName” value=”${jdbc.driverClassName}” />
<property name=”url” value=”${jdbc.url}” />
<property name=”username” value=”${jdbc.username}” />
<property name=”password” value=”${jdbc.password}” />
</bean>

<context:property-placeholder location=”jdbc.properties”/>

<bean class=”org.springframework.jdbc.core.JdbcTemplate”>
<constructor-arg ref=”dataSource” />
</bean>

</beans>

外部ファイル(jdbc.properties)

发表评论