独角兽企业重金招聘Python工程师标准>>>
首先当然是访问数据库,以前学习php的时候,就是从留言板、登录等功能开始学习的,之所以这样学习无非就是因为从前台到后台,该有的全都有了,完整而简洁的生命周期。
用的是jdbcTemplate,这还是最近才了解到的。数据库是Oracle 11g,恰好虚拟机里装了,所以就用上了。
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下报了“找不到文件”之类的错误。
applicationContext.xml如下:
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans /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();}}}
成功访问了数据库。 代码是复制的,所以贴上来了。这最初的代码可以测试一下。以后的代码更愿意贴图上来,不然在浏览器和在线编辑器里双滚动条滚得麻烦得很。