spring操作數據庫如此簡單

以前一直都沒有試過,前幾天打算把wordpress換成自己寫的程序,就想到了數據的導入和導出,首先想到的是用數據庫工具來導。可是覺得有些麻煩,我自己的程序是用spring+hibernate的。後來我就試了一下spring的JdbcTemplate,就和HibernateTemplate一樣的好用。首先增加一個連接到wp數據庫的dataSource
    <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
        
<property name="driverClassName"><value>org.hibernate.dialect.MySQLDialect</value></property>
        
<property name="url">
            
<value>jdbc:mysql://192.168.0.240:3306/wordpressωuseUnicode=true&amp;characterEncoding=utf8</value>
            
</property>
        
<property name="username"><value>root</value></property>
        
<property name="password"><value></value></property>
    
</bean>

    然後在轉換程序裏面get這個dataSource,new 一個JdbcTemplate(dataSource2),這樣就ok了。很簡單吧。

    public void testCopyData() throws Exception{
        DataSource ds 
= (DataSource)applicationContext.getBean("dataSource2");
        
        CategoryManager cateManager 
= (CategoryManager) applicationContext.getBean("categoryManager");
        
        JdbcTemplate jt 
= new JdbcTemplate(ds);
        System.out.println(
"Total posts:"+jt.queryForInt("select count(*) from wp_posts"));
        assertNotNull(ds);
        
        List cates 
= jt.queryForList("select * from wp_categories");
        
int i= 0;
        
for(Iterator ite = cates.iterator(); ite.hasNext();){
            i
++;
            Map result 
= (Map) ite.next();
            Category cate 
= new Category();
            cate.setName((String)result.get(
"cat_name"));
            cate.setOrder(i);
            
if(i==1)
                cate.setDefaultCategory(
true);
            cateManager.saveCategory(cate);
            System.out.println(
"cat_name:"+result.get("cat_name")+"\n");
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章