首先固然是访问数据库,之前学习php的时候,就是从留言板、登陆等功能开始学习的,之因此这样学习无非就是由于从前台到后台,该有的全都有了,完整而简洁的生命周期。 php
用的是jdbcTemplate,这仍是最近才了解到的。数据库是Oracle 11g,刚好虚拟机里装了,因此就用上了。 java
public class PlanDao { private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public Connection getConnection(){ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource springDataSource = (DataSource)ctx.getBean("springDataSource"); JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate"); /*jdbcTemplate.setDataSource(springDataSource); setJdbcTemplate(jdbcTemplate); */ DataSource dataSource = jdbcTemplate.getDataSource(); Connection conn = null; try { conn = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public ResultSet queryPersons(String sql){ ResultSet rs = null; try { Connection connection = getConnection(); Statement st = connection.createStatement(); rs = st.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } }
代码是复制别人的,倒也简洁明了,只是getConnection()方法第一行,本来复制来的时候ctx是用ApplicationContext定义的,可是ApplicationContext好像并非后来new的对象的父类,报了错,因此修改了这么一点地方。另外applicationContext.xml我是放在了src目录下(Eclipse的动态网站工程)才试验成功的,放WEB-INF下报了“找不到文件”之类的错误。 spring
applicationContext.xml以下: sql
<?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 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="springDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver"> </property> <property name="url" value="jdbc:oracle:thin:@192.168.1.152:1521:orcl"> </property> <property name="username" value="plan"></property> <property name="password" value="admin"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="false" autowire="default" dependency-check="default"> <property name="dataSource"> <ref bean="springDataSource" /> </property> </bean> </beans>
用来测试的main方法类以下 数据库
public class Main { public static void main(String[] args) { PlanDao pd = new PlanDao(); ResultSet rs = pd.queryPersons("select * from plan"); int n = 0; try { while (rs.next()) { n++; System.out.println("id = " + rs.getString(1)); System.out.println("name = " + rs.getString(2)); System.out.println("gender = " + rs.getString(3)); System.out.println("*******************************"); } System.out.println("数据库中共有记录 " + n + " 条"); } catch (SQLException e) { e.printStackTrace(); } } }成功访问了数据库。 代码是复制的,因此贴上来了。这最初的代码能够测试一下。之后的代码更愿意贴图上来,否则在浏览器和在线编辑器里双滚动条滚得麻烦得很。