1. 程式人生 > >一個簡單的從txt檔案中讀取資料插入資料庫

一個簡單的從txt檔案中讀取資料插入資料庫

一: 首先我們應該先·建一個Dynamic web project 工程。

二: 定義一個讀檔案操作 package com.what.files;
在這裡我們要用到用於讀取本地檔案中的位元組資料的FileInputStream,FileInputStream繼承了InputStream。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;


public class ReadFile {


public static void readTxtFile(String filePath){

InfoBean infoBean = new InfoBean();

try {
String encoding = "utf-8";
File file = new File("D:\\資料.txt");
if(file.isFile() && file.exists()){//判斷該檔案是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file) , encoding);
BufferedReader buffereReader = new BufferedReader(read);
String lineTxt = null;
OperationDB operationDB = new OperationDB();
lineTxt = buffereReader.readLine();
while((lineTxt = buffereReader.readLine()) != null){
String[] s = lineTxt.split("\\|");
infoBean.setSeqNo(new BigDecimal(s[0]));
                //(s[0].toString());
                infoBean.setBillNo(s[1].toString());
                infoBean.setPolicyNo(s[2].toString());
                infoBean.setCertiNo(s[3].toString());         
                infoBean.setAmount(new BigDecimal(s[4]));
                operationDB.addRcorder(infoBean);
                System.out.println(lineTxt);
}
read.close();
} else {
            System.out.println("找不到指定的檔案");
        }
    } catch (Exception e) {
        System.out.println("讀取檔案內容出錯");
        e.printStackTrace();
    }
}
}

三:寫一個連結資料庫的類

建立jdbc資料庫的一般步驟為:

@1.註冊驅動(載入驅動,此次載入只做一次),在連結資料庫之前首先要載入連結資料庫的驅動JVM(即java虛擬機器)

通過Java.lang.Class中的forName(String ClassName)方法實現.

如:【

try{

Class.forName("com.mySql.jdbc.Driver");

}catch(ClassNotFoundException e){

System.out.println("載入失敗,找不到驅動程式");

e.printStackTrace();

}

@2.提供連結資料庫jdbc的URL

連結URL定義了連線資料庫時的協議,子協議,資料來源標識。

格式:協議,子協議,資料來源標識。

協議:以jdbc開始。

子協議:是橋連線的資料庫程式或資料庫管理系統的名稱

資料來源標識:標記找到資料庫來源的地址與連結埠;

如:
jdbc : mySql;

/localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
   useUnicode=true:表示使用Unicode字符集。如果characterEncoding設定為   
   gb2312或GBK,本引數必須設定為true 。characterEncoding=gbk:字元編碼方式。
@3.

建立資料庫的來連結。

首先向javav.sql.DriverManag獲得Connection連結物件,該物件表示一個數據庫的連結。

使用DriverManage的一個getConnection(String url, String username,String password)的方法傳入指定要連結的資料庫的地址,使用者名稱,密碼。

 String url = "jdbc:mysql://localhost:3306/test" ;    
     String username = "root" ;   
     String password = "root" ;   
try{   
    Connection con =    
             DriverManager.getConnection(url , username , password ) ;   
     }catch(SQLException se){   
    System.out.println("資料庫連線失敗!");   
    se.printStackTrace() ;   
     }   

@4.

建立一個Statement

要執行SQL 語句,必須獲得java.sal.Statement例項。Statement例項分為三種類型(1)執行靜態SQL,通過Statement例項實現。

(2)執行動態SQL,通過PareStatement例項實現。

(3)執行資料庫儲存過程,通過CallableStatement例項實現。

Statement stmt = con.createStatement();

PareparedStatement pstmt = con.prepareStatement(sql);

CallableStatement  cstmt = con.prepareCall("{CALL demoSp(?,?)}");

@5.執行Sql語句

statement提供了三種執行SQL語句的方法:excute,excuteQuery,excuteUpdate,

(1).ResultSet  excuteQuery(String sqlString),執行查詢資料庫的SQL語句,返回一個ResultSet物件。

(2).int excuteUpdate(String sqlString),用於執行InSERT,UPDATE,DELETE,以及SQL DDL語句如CREATE TABLE,DROP TABLE。

(3).excute(String sqlString)用於執行返回多個結果集,多個更新計數或者二者組合的語句。

  •      ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;   
  •     int rows = stmt.executeUpdate("INSERT INTO ...") ;   
  •     boolean flag = stmt.execute(String sql) ;   

@6.處理結果

(1)執行本次更新影響到的記錄數

(2)執行返回的結果是一個ResultSet物件。

  • 【 ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些   
  •       行中資料的訪問。   
  •     • 使用結果集(ResultSet)物件的訪問方法獲取資料:   
  •      while(rs.next()){   
  •          String name = rs.getString("name") ;   
  •     String pass = rs.getString(1) ; // 此方法比較高效  
  •      }   
  •     (列是從左到右編號的,並且從列1開始)   

@7關閉資料庫連線

操作完成之後要把使用過的jdbc物件全部關閉。以釋放jdbc連結資源,關閉順序和宣告順序相反。

  • 1、關閉記錄集   
  •      2、關閉宣告   
  •      3、關閉連線物件   
  •           if(rs != null){   // 關閉記錄集  
  •         try{   
  •             rs.close() ;   
  •         }catch(SQLException e){   
  •             e.printStackTrace() ;   
  •         }   
  •           }   
  •           if(stmt != null){   // 關閉宣告  
  •         try{   
  •             stmt.close() ;   
  •         }catch(SQLException e){   
  •             e.printStackTrace() ;   
  •         }   
  •           }   
  •           if(conn != null){  // 關閉連線物件  
  •          try{   
  •             conn.close() ;   

         }catch(SQLException e){               e.printStackTrace() ;            }             }


package com.files.insert;




import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;




public class BeyondbConnection {
public static Connection getConnection() {


Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://10.8.9.11:3306/trshdev_dw_aml";
String user = "trshdev_dw_aml";
String password = "123456";


try {


con = DriverManager.getConnection(url, user, password);
} catch (SQLException ex) {
Logger.getLogger(BeyondbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;


}
}

package com.files.insert;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class OperationDB {
private Connection con = null;
     public void addRcorder(InfoBean infoBean) throws SQLException {
         if(con ==null){
              con = BeyondbConnection.getConnection();
         }
       
        String sql = "insert into t_pa_nb_list (seq_no,bill_no,policy_no,certi_no,amount) values(?,?,?,?,?)";
     
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setBigDecimal(1, infoBean.getSeqNo());
            //setString(1, infoBean.getSeqNo());
            pstmt.setString(2, infoBean.getBillNo());
            pstmt.setString(3, infoBean.getPolicyNo());
            pstmt.setString(4, infoBean.getCertiNo());
            pstmt.setBigDecimal(5, infoBean.getAmount());
        
           
            pstmt.executeUpdate();   
    }
}

四:定義一個類用於將讀取的內容存到資料庫中

package com.files.insert;


import java.math.BigDecimal;


public class InfoBean {


private BigDecimal seqNo;
private String billNo;
private String policyNo;
private String certiNo;
private BigDecimal amount;
public BigDecimal getSeqNo() {
return seqNo;
}
public void setSeqNo(BigDecimal seqNo) {
this.seqNo = seqNo;
}
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public String getPolicyNo() {
return policyNo;
}
public void setPolicyNo(String policyNo) {
this.policyNo = policyNo;
}
public String getCertiNo() {
return certiNo;
}
public void setCertiNo(String certiNo) {
this.certiNo = certiNo;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}

五: 主函式:

package com.files.insert;


public class Text {



public static void main(String[] args){
  String filePath = "D:\\資料.txt";
      ReadFile readFile=new ReadFile();  
      readFile.readTxtFile(filePath);
}
}