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