WebCrawler Java小爬爬 从入门到放弃 第四章

这篇可看可不看。
:)

数据库相关事务

配置好SQL Server2012,MySQL也可以 关系数据库就行
用外观模式写一个数据库连接类 DB_Link
博主原来自己写过一个DB_Link
但是这次不同 因为我们在爬网页的时候,爬下来的处理后的信息
会常去和数据库通信
所以Statement类已经不适用了 用PreparedStatement
顾名思义预处理过的Statement

写一个数据库链接信息类

public class DB_link_Info {
    public static final String driverName = 
            "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    public static final String dbURL = 
            "jdbc:sqlserver://localhost:1433;DatabaseName=WebCrawler";
    public static final String userName =
            "sa";
    public static final String userPwd =
            "729757710";
}

然后写DB_Link

import java.sql.*;

public class DB_Link {

    private Statement sta;
    private ResultSet rs;
    private static Connection con;
    private String sql;
    private ResultSetMetaData rsmd;

    public static Connection getConnection() {
        try {
            Class.forName(DB_link_Info.driverName);
            con = DriverManager.getConnection(DB_link_Info.dbURL,
                    DB_link_Info.userName,DB_link_Info.userPwd);
            System.out.println("Successfully connect to the database.");
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        return con;
    }

    public void close() throws Throwable{
        System.gc();
    }

    public void setSQL(String sql) throws SQLException{
        this.sql = sql;
        rs = sta.executeQuery(sql) ; 
        rsmd = rs.getMetaData();
    }

    public String getSQL(){return sql;}

    public ResultSet getRS(){return rs;}

    public ResultSetMetaData getRSMD(){return rsmd;}

    public void execQuery(){
        try {
            sta.executeQuery(sql);
        } catch (SQLException e) {
            System.out.print("插入或跟新失败");
        }
    }

    public void execQuery(String sql){
        try {
            sta.executeQuery(sql);
        } catch (SQLException e) {
            System.out.print("插入或跟新失败");
        }
    }
}

将getConnection()定义为静态方法,方便调用。

博主要去看设计模式了。
大家晚安。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值