IPInfoToDB.java~51~
上传用户:liming9091
上传日期:2014-10-27
资源大小:3376k
文件大小:2k
源码类别:

Java编程

开发平台:

Java

  1. package tsinghuaip;
  2. import java.sql.*;
  3. import java.util.*;
  4. import java.io.*;
  5. public class IPInfoToDB {
  6.     private String strTxtFileName; //IP地址文本文件名
  7.     private Connection conn = null;
  8.     private Statement stmt = null;
  9.     public IPInfoToDB() {
  10.         strTxtFileName = new String();
  11.     }
  12.     //设置文本文件名
  13.     public void SetTxtFileName(String strFileName) {
  14.         strTxtFileName = strFileName;
  15.     }
  16.     public void SaveIPToDB() throws Exception {
  17.         String strSeparator = "|"; //the separator of the text file field
  18.         String strTmp = "";
  19.         //进行数据库得连接
  20.         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  21.         String url = "jdbc:microsoft:sqlserver://localhost:1433;" +
  22.             "DatabaseName=CampusIP";
  23.         conn = DriverManager.getConnection(url, "sa", "");
  24.         stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
  25.                                     ResultSet.CONCUR_UPDATABLE);
  26.         //从文本文件中读取数据
  27.         BufferedReader inTxt = new BufferedReader(new FileReader(
  28.             strTxtFileName));
  29.         while ( (strTmp = inTxt.readLine()) != null) {
  30.             StringTokenizer strToken = new StringTokenizer(strTmp, "|");
  31.             String arrTmp[];
  32.             arrTmp = new String[3];
  33.             for (int i = 0; i < 3; i++)
  34.                 arrTmp[i] = new String("");
  35.             int index = 0;
  36.             while (strToken.hasMoreElements()) {
  37.                 strTmp = (String) strToken.nextElement();
  38.                 strTmp = strTmp.trim();
  39.                 arrTmp[index++] = strTmp;
  40.             }
  41.             //下面就是将这些数据写进数据库
  42.             String SQL =
  43.                 "insert IPInfo(STARTIP,ENDIP,LOCAL) "
  44.                 + " values('" + arrTmp[0] + "', '"
  45.                 + arrTmp[1] + "','"
  46.                 + arrTmp[2] + "')";
  47.             stmt.execute(SQL);
  48.         }
  49.         rs.close();
  50.         stmt.close();
  51.         conn.close();
  52.     }
  53. }