ipinfotodb.java~52~

来自「JAVA课程设计需要」· JAVA~52~ 代码 · 共 68 行

JAVA~52~
68
字号
package tsinghuaip;

import java.sql.*;
import java.util.*;
import java.io.*;

public class IPInfoToDB {
    private String strTxtFileName; //IP地址文本文件名
    private Connection conn = null;
    private Statement stmt = null;

    public IPInfoToDB() {
        strTxtFileName = new String();
    }

    //设置文本文件名
    public void SetTxtFileName(String strFileName) {
        strTxtFileName = strFileName;
    }

    public void SaveIPToDB() throws Exception {
        String strSeparator = "|"; //the separator of the text file field
        String strTmp = "";

        //进行数据库得连接
        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
        String url = "jdbc:microsoft:sqlserver://localhost:1433;" +
            "DatabaseName=CampusIP";
        conn = DriverManager.getConnection(url, "sa", "");
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                                    ResultSet.CONCUR_UPDATABLE);

        //从文本文件中读取数据
        BufferedReader inTxt = new BufferedReader(new FileReader(
            strTxtFileName));

        while ( (strTmp = inTxt.readLine()) != null) {
            StringTokenizer strToken = new StringTokenizer(strTmp, "|");

            String arrTmp[];
            arrTmp = new String[3];
            for (int i = 0; i < 3; i++)
                arrTmp[i] = new String("");

            int index = 0;

            while (strToken.hasMoreElements()) {
                strTmp = (String) strToken.nextElement();
                strTmp = strTmp.trim();
                arrTmp[index++] = strTmp;
            }

            //下面就是将这些数据写进数据库
            String SQL =
                "insert IPInfo(STARTIP,ENDIP,LOCAL) "
                + " values('" + arrTmp[0] + "', '"
                + arrTmp[1] + "','"
                + arrTmp[2] + "')";

            stmt.execute(SQL);
        }

        stmt.close();
        conn.close();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?