1.導入Spring JDBC的依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
2.創建一個JDBCHelper類
import java.util.HashMap;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/**
*
* @author hu
*/
public class JDBCHelper {
public static HashMap<String, JdbcTemplate> templateMap
= new HashMap<String, JdbcTemplate>();
public static JdbcTemplate createMysqlTemplate(String templateName,
String url, String username, String password,
int initialSize, int maxActive) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
JdbcTemplate template = new JdbcTemplate(dataSource);
templateMap.put(templateName, template);
return template;
}
public static JdbcTemplate getJdbcTemplate(String templateName){
return templateMap.get(templateName);
}
}
可以調用JDBCHelper的getJdbcTemplate方法來獲取一個JdbcTemplate,考慮到有些爬蟲可能會用到多個數據庫,這裏可以爲每個JdbcTemplate指定名稱,如果已經創建了一個名爲xxx的JdbcTemplate,第二次調用getJdbcTemplate(xxx)時,不會二次創建,而是返回已經創建的JdbcTemplate。
3.初始化一個JdbcTemplate
例如我們要創建一個包含了id,url,title,html四列的表:
JdbcTemplate jdbcTemplate = null;
try {
jdbcTemplate = JDBCHelper.createMysqlTemplate("mysql1",
"jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=utf8",
"root", "password", 5, 30);
/*創建數據表*/
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS tb_content ("
+ "id int(11) NOT NULL AUTO_INCREMENT,"
+ "title varchar(50),url varchar(200),html longtext,"
+ "PRIMARY KEY (id)"
+ ") ENGINE=MyISAM DEFAULT CHARSET=utf8;");
System.out.println("成功創建數據表 tb_content");
} catch (Exception ex) {
jdbcTemplate = null;
System.out.println("mysql未開啓或JDBCHelper.createMysqlTemplate中參數配置不正確!");
}
4.在WebCollector的visit方法中使用jdbcTemplate持久化數據
if (jdbcTemplate != null) {
int updates=jdbcTemplate.update("insert into tb_content"
+" (title,url,html) value(?,?,?)",
title, page.getUrl(), page.getHtml());
if(updates==1){
System.out.println("mysql插入成功");
}
}
通過捐款支持WebCollector
維護WebCollector及教程需要花費較大的時間和精力,如果你喜歡WebCollector的話,歡迎通過捐款的方式,支持開發者的工作,非常感謝!
你可以使用支付寶錢包掃描下方的二維碼進行捐款, 或者通過向支付寶帳號 [email protected]轉帳進行捐款。