以前一直都没有试过,前几天打算把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 & characterEncoding=utf8 </ value >
</ property >
< property name ="username" >< value > root </ value ></ property >
< property name ="password" >< value ></ value ></ property >
</ bean >
< property name ="driverClassName" >< value > org.hibernate.dialect.MySQLDialect </ value ></ property >
< property name ="url" >
< value > jdbc:mysql://192.168.0.240:3306/wordpressωuseUnicode=true & 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 " );
}
}
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 " );
}
}