1. 程式人生 > >用java實現從txt文字檔案批量匯入資料至資料庫

用java實現從txt文字檔案批量匯入資料至資料庫

今天同事讓我準備一個專案的測試資料,要向一個表中插入上千條記錄,並且保證每條記錄內容不同,如果用手工一條一條插入肯定是不可能,也不會有哪個SB去做這樣的事,我最開始想到了用迴圈,但要求插入的記錄內容不能相同,用迴圈實現比較麻煩,於是我想到了將記錄從文字檔案匯入至資料庫(其實SQLServer可利用sql語句實現匯入xls或txt檔案,在這就不具體說明了),寫個簡單的具有解析文字檔案並將解析結果插入資料庫的類,實現批量插入記錄的功能。

1、將資料按一定規律錄入到一個文字檔案,每一行代表一條記錄。

下面是資料庫建表SQL:
CREATE TABLE t_FltPsgInfo  -- 航班乘客資訊

(

    FltNum  VARCHAR(10), -- 航班號

    FltLine  VARCHAR(30),  -- 航線

    FltDate  VARCHAR(10),  -- 日期

    PsgName  VARCHAR(30),  -- 姓名

    PsgType  VARCHAR(30), -- 乘客型別,數字表示,目前是1-13

    PsgSex  VARCHAR(1),  -- 0 男  1 女

    PsgCab  VARCHAR(1),  -- 幾等艙, F/Y  艙位按字母順序排列

    PsgSeatNo  VARCHAR(5),-- 座位號 2A,22F,根據這個得到一排有多少個座位,共有多少排座位資訊

    PsgInfo  VARCHAR(2048) -- 詳細資訊,可能很長

)

我們將向表t_FltPsgInfo中插入1000條記錄。

新建一個文字檔案,每一行代表一條記錄,如:

HU7804,廣州-北京,2007-07-18,謝麗珍,3,1,C,3A,服務保障資訊:未用餐隨行人員…

其中以“,”作為欄位的分隔標誌,我們在解析這個文字檔案時將根據“,”來拆分欄位值。

按照上面的格式,將要插入的資料輸入到文字檔案中,注意,是每一行代表一條記錄,或者你已有從資料庫匯出的文字檔案,那你就只需找到檔案的規律,稍作調整就行了。

2、編寫Java原始碼

1》資料庫操作類InsertDB.java

package test; 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement; 

public class InsertDB {

    private static final String user = "sa";

    private static final String pwd = "sa";

    private static final String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=hhfly";

    private static final String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";

    public static Connection getCon() {

        Connection con = null;

        try {

            Class.forName(driver).newInstance();

            con = DriverManager.getConnection(urluserpwd);

            if (con != null) {

                System.out.println("你已連線到資料庫:" + con.getCatalog());

            }

        } catch (Exception e) {

            System.out.println("連線資料庫失敗!");

            e.printStackTrace();

        }

        return con;

    } 

    public boolean insertDB(String FltNum, String FltLine, String FltDate,

            String PsgName, String PsgType, String PsgSex, String PsgCab,

            String PsgSeatNo, String PsgInfo) {

        Connection con = null;

        Statement stm = null;

        boolean flag = false;

        String sql = "insert into t_FltPsgInfo values('" + FltNum + "','"

                + FltLine + "','" + FltDate + "','" + PsgName + "','" + PsgType

                + "','" + PsgSex + "','" + PsgCab + "','" + PsgSeatNo + "','"

                + PsgInfo + "')";

        try {

            con = getCon();

            stm = con.createStatement();

            int i = stm.executeUpdate(sql);

            if (i > 0) {

                flag = true;

                System.out.println(flag + "插入資料成功!");

            }

        } catch (Exception e) {

            flag = false;

            e.printStackTrace();

        } finally {

            close(null, stm, con);

        }

        return flag;

    }

    //關閉相關連線

    public void close(ResultSet rs, Statement stm, Connection con) {

        if (rs != null)

            try {

                rs.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        if (stm != null)

            try {

                stm.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        if (con != null)

            try {

                con.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

    }

}

2》資料採集類DataGather.java

package test; 

import java.io.RandomAccessFile;

import java.io.UnsupportedEncodingException; 

public class DataGather {

    private static final String path = "src/resource/test";

    public static final String openFileStyle = "r";

    public static final String fieldLimitChar = ",";

    public static final int fieldAllCount = 9;

    private int count;

    private String FltNum;

    private String FltLine;

    private String FltDate;

    private String PsgName;

    private String PsgType;

    private String PsgSex;

    private String PsgCab;

    private String PsgSeatNo;

    private String PsgInfo;

    /*

     * 功能:解析文字檔案

     */

    public void loadFile() {

        try {

            RandomAccessFile raf = new RandomAccessFile(pathopenFileStyle);

            String line_record = raf.readLine();

            while (line_record != null) {

                // 解析每一條記錄

                parseRecord(line_record);

                line_record = raf.readLine();

            }

            System.out.println("共有合法的記錄" + count + "條");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /*

 * 功能:具體解析每一條記錄,這裡可以增加很多對記錄的解析判斷條件,如是否為字母、

* 數字、email等。

     */

    private void parseRecord(String line_record) throws Exception {

     //拆分記錄

        String[] fields = line_record.split(fieldLimitChar);

        if (fields.length == fieldAllCount) {

            FltNum = tranStr(fields[0]);

            FltLine = tranStr(fields[1]);

            FltDate = tranStr(fields[2]);

            PsgName = tranStr(fields[3]);

            PsgType = tranStr(fields[4]);

            PsgSex = tranStr(fields[5]);

            PsgCab = tranStr(fields[6]);

            PsgSeatNo = tranStr(fields[7]);

            PsgInfo = tranStr(fields[8]);

            System.out.println(FltNum + " " + FltLine + " " + FltDate + " "

                    + PsgName + " " + PsgType + " " + PsgSex + " " + PsgCab

                    + " " + PsgSeatNo + " " + PsgInfo);

            InsertDB db = new InsertDB();

            db.insertDB(FltNum, FltLine, FltDate, PsgName, PsgType, PsgSex,

                    PsgCab, PsgSeatNo, PsgInfo);

            count++;

        }

    }

    private String tranStr(String oldstr) {

        String newstr = "";

        try {

            newstr = new String(oldstr.getBytes("ISO-8859-1"), "GBK");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return newstr;

    }

}

3》測試類Test.java

package test;

public class Test {

    public static void main(String[] args) {

        try {

            DataGather gather = new DataGather ();

            gather.loadFile();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

執行測試類,得到結果:

  

向資料庫插入資料成功!