2016-11-06 9 views
1

私が取り組んでいるプロジェクトで助けが必要です。プロジェクトの最初の部分は、偽のデータを生成し、それをCSVテキストファイルに書き込むユーティリティ/ツールを作成することです。この部分はうまく動作しています。 (それは場合に役立ちます)ここで JavaとMySQLデータベースのファイル読み込み

import sys 
from faker import Factory 
fake = Factory.create() 

x = 1 
param1 = int(sys.argv[1]) 
f = open('myfile.txt','w') 
for x in range (0,param1): 
f.write(fake.first_name() + "," + fake.last_name() + "," + fake.job() + "," + fake.email() + "," 
    + fake.street_address() + "," + fake.city() + "," + fake.state() + "," + fake.state_abbr() + "," 
    + fake.zipcode() + "," + fake.credit_card_provider() + "," 
    + fake.credit_card_number() + "," + fake.phone_number() + "\n") 

f.close() 
ここ

コンパイル時に出力します何だそのためのコードです:

William,James,Careers information officer,[email protected],9448 Rodriguez Brook Apt. 796,South Lynnbury,South Carolina,VA,26103,JCB 16 digit,3112583369273283,1-002-827-0311x681 

Luis,Martin,Air cabin crew,[email protected],6154 James Cove,Christianberg,New York,RI,37208,JCB 15 digit,378433042568763,+42(0)3011107909 

Jose,Jones,Make,[email protected],431 Jessica Pass,East Robertburgh,Texas,SC,46458,Mastercard,4800941995105607,(047)981-1856x1825 

Mary,Pope,Field seismologist,[email protected],00799 Tracy Trace,Robinburgh,Rhode Island,HI,68855,JCB 16 digit,6011260007331949,+66(4)4995888616 

Jennifer,Villanueva,Tax adviser,[email protected],271 Simmons Mountains,Boydmouth,Nebraska,NM,98981,JCB 16 digit,210077713575961,639.575.1338x414 

余分なスペースを各ラインの間に、私は読みやすさのためにここでそれらを追加しました。

プロジェクトの次の部分は、非構造化データをCSVテキストファイルから正規化されたデータベースにインポートするアプリケーションをJavaで開発することです。

私はいくつかのJavaコードを持っていますが、それは私が考えている方法では機能しません(BTW、どうすればよいのかについて私の考えを修正してください)。私はそれが動作するはず考えている方法は、java

  • へのデータはその.setString機能と一緒にテーブルにデータをインポートするSQL文を作成するために準備された文関数を使用し

    1. インポートですそれのために必要です

    しかし、それは正しく動作していません。最初にコードを入力し、次に何が起こっているのかを説明します:

    package com.company; 
    
    import java.io.File; 
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.PreparedStatement; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
    import java.util.ArrayList; 
    import java.util.Scanner; 
    
    public class Main { 
    
        private static Connection connect() { 
         Connection mysql = null; //sets values to null before actually attempting a connection 
         PreparedStatement pst = null; 
         ResultSet data = null; 
         try 
         { 
          Class.forName("com.mysql.jdbc.Driver"); 
          String connectionStringURL = "jdbc:mysql://us-cdbr-azure-west-b.cleardb.com:3306/acsm_0a00c1270f36f77"; //database name 
          mysql = DriverManager.getConnection(connectionStringURL, "username", "password"); //username, password 
    
          if (mysql == null) //check to make sure that it actually connected 
           System.out.println("Connection Failed"); 
          else 
           System.out.println("Success"); 
    
         } 
         catch (Exception ex) //catches connection failure exception 
         { 
          ex.printStackTrace(); 
         } 
         return mysql; 
        } 
    
        public static void main(String[] args) throws Exception { 
         String filename = "/Desktop/myfile.txt"; 
    
         PreparedStatement pstmt = null; 
         Connection mysql = connect(); 
         try 
         { 
          pstmt = mysql.prepareStatement("INSERT INTO Customer (First Name, Last Name, Job, Email, Phone Number) VALUES (?,?,?,?,?)"); 
    
          Scanner s = new Scanner(new File("/Desktop/myfile.txt")); 
         ArrayList<String> list = new ArrayList<String>(); 
          while (s.hasNextLine()) 
          { 
           list.add(s.nextLine()); 
          } 
          System.out.println(list); 
          s.close(); 
         } 
         catch (SQLException e) 
         { 
          e.printStackTrace(); 
         } 
        } 
    } 
    

    最初の関数は明らかに私のデータベース接続関数ですが、問題はありません。

    2番目の機能は、問題が発生している場所です。現時点では、SQLスクリプトがすでに用意されています。しかし、実際にはまだ使用されていません。私が最初にやろうとしているのは、ファイルを行ごとに読み取ることです。次に、各フィールドについてそれを解析します。

    各列の要素を持っているデータクラスを作成し、私はそれを行うにはどのように私の友人に尋ね、彼がラインによって

    1. 読むファイルの行に言った、カンマで分割し、配列
    2. に渡します作成された各ラインのアレイのためのあなたのファイル
    3. で、
    4. は、JDBC
    5. 書き込みINSERTステートメントのbatchExecuteを()ルックアップするデータクラスのオブジェクトを作成し、
    6. を実行します210

    「配列に渡す」と言われる最初のステップでは、配列またはArrayListだけを使用し、いずれの場合でも各レコード/行に独自の配列/配列があることを意味しますか?

    他の手順を実行する方法がわかりません。私はインターネット上で答えを探してきましたが、私は不足しています。

    私は何か言及することを忘れているとは思わないが、私が言ったことについてさらに明確にする必要があれば、私が何を意味するかを説明して喜んで喜んでいる。どんな助けもありがとうございます。

    ありがとうございます。

  • 答えて

    1

    私は、csvファイルを読み書きするためにcsvパーサを使用することをお勧めします。以下は、あなたが以下の

    public class Customer { 
    
        private String firstName; 
        private String lastName; 
        private String job; 
        private String email; 
        private String phone; 
    
        public Customer(String firstName, String lastName, String job, String email, String phone) { 
         this.firstName = firstName; 
         this.lastName = lastName; 
         this.job = job; 
         this.email = email; 
         this.phone = phone; 
        } 
    
        public String getFirstName() { 
         return firstName; 
        } 
    
        public void setFirstName(String firstName) { 
         this.firstName = firstName; 
        } 
    
        public String getLastName() { 
         return lastName; 
        } 
    
        public void setLastName(String lastName) { 
         this.lastName = lastName; 
        } 
    
        public String getJob() { 
         return job; 
        } 
    
        public void setJob(String job) { 
         this.job = job; 
        } 
    
        public String getEmail() { 
         return email; 
        } 
    
        public void setEmail(String email) { 
         this.email = email; 
        } 
    
        public String getPhone() { 
         return phone; 
        } 
    
        public void setPhone(String phone) { 
         this.phone = phone; 
        } 
    } 
    
    のようなクラスを必要とするデータクラスを利用したい場合は opencsv

    import com.opencsv.CSVReader; 
    import java.io.FileReader; 
    import java.io.IOException; 
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.PreparedStatement; 
    import java.sql.SQLException; 
    import java.util.ArrayList; 
    import java.util.List; 
    
    public class NewClass1 { 
        public static void main(String[] args) { 
         try { 
    
          String fileName = "yourfile.csv"; 
          List<String[]> customerList = readWholeCsvFile(fileName); 
          Connection conn = getConnection(); 
          persistWithOutDataClass(conn,customerList); 
    
         } catch (IOException ex) { 
          ex.printStackTrace(); 
         } catch (SQLException ex) { 
          ex.printStackTrace(); 
         } 
        } 
    
        public static List<String[]> readWholeCsvFile(String fileName) throws IOException{ 
         List<String[]> myEntries = new ArrayList<>(); 
         CSVReader reader = new CSVReader(new FileReader(fileName), ',' ,'\'', 1); 
         myEntries = reader.readAll(); 
         return myEntries;   
        } 
    
        public static List<Customer> readCsvFileLineByLine(String fileName) throws IOException{ 
         List<Customer> customerList = new ArrayList<>(); 
         String [] nextLine; 
         CSVReader reader = new CSVReader(new FileReader(fileName), ',' ,'\'', 1); 
         while ((nextLine = reader.readNext()) != null) {   
          customerList.add(new Customer(nextLine[0], nextLine[1], nextLine[2], nextLine[3], nextLine[4])); 
         }  
         return customerList;   
        } 
    
        private static Connection getConnection() { 
         Connection conn = null; //sets values to null before actually attempting a connection    
         try{ 
          Class.forName("com.mysql.jdbc.Driver"); 
          String connectionStringURL = "jdbc:mysql://us-cdbr-azure-west-b.cleardb.com:3306/acsm_0a00c1270f36f77"; //database name 
          conn = DriverManager.getConnection(connectionStringURL, "username", "password"); //username, password 
          if (conn == null) //check to make sure that it actually connected 
           System.out.println("Connection Failed"); 
          else 
           System.out.println("Success"); 
         } 
         catch (Exception ex){ 
          ex.printStackTrace(); 
         } 
         return conn; 
        } 
    
        private static void persistWithOutDataClass(Connection conn, List<String[]> customerList) throws SQLException{ 
         String insertStatement = " insert into Customer (First Name, Last Name, Job, Email, Phone Number) values (?, ?, ?, ?, ?)"; 
         PreparedStatement preparedStmt = conn.prepareStatement(insertStatement); 
         for(String[] row : customerList){ 
          preparedStmt.setString (1, row[0]); 
          preparedStmt.setString (2, row[1]); 
          preparedStmt.setString (3, row[2]); 
          preparedStmt.setString (4, row[3]); 
          preparedStmt.setString (5, row[11]); 
          preparedStmt.addBatch(); 
         } 
         preparedStmt.executeBatch(); 
        } 
    
        private static void persistWithDataClass(Connection conn, List<Customer> customerList) throws SQLException{ 
         String insertStatement = " insert into Customer (First Name, Last Name, Job, Email, Phone Number) values (?, ?, ?, ?, ?)"; 
         PreparedStatement preparedStmt = conn.prepareStatement(insertStatement); 
         for(Customer cust : customerList){ 
          preparedStmt.setString (1, cust.getFirstName()); 
          preparedStmt.setString (2, cust.getLastName()); 
          preparedStmt.setString (3, cust.getJob()); 
          preparedStmt.setString (4, cust.getEmail()); 
          preparedStmt.setString (5, cust.getPhone()); 
          preparedStmt.addBatch(); 
         } 
         preparedStmt.executeBatch(); 
        } 
    } 
    

    を使用した例があります

    関連する問題