2016-03-02 134 views
0

我想讀取txt文件內容並將其插入到我的sql表中。讀取文本文件並將輸出插入到mysql表中

我通過編碼做到了這一點,但它顯示出一些錯誤。也嘗試通過查詢,但它在表中顯示爲空。

查詢 -

INSERT INTO patent_uspto_tmp (pinv) VALUES (LOAD_FILE('/home/gaurav/Documents/pinv.txt')); 

碼 -

try{ 
     String arr[]=null; 
    String outputFile = "/home/gaurav/Documents/pinv.txt"; 

    FileReader fileReader = new FileReader(outputFile); 
    BufferedReader bufferedReader = new BufferedReader(fileReader); 
    String inputLine; 
    List<String> lineList = new ArrayList<String>(); 
    while ((inputLine = bufferedReader.readLine()) != null) { 
     lineList.add(inputLine); 
    } 
    fileReader.close(); 

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

    Connection con=DriverManager.getConnection( 
    "jdbc:mysql://localhost:3306/patent","root","india2000"); 
    for (int i = 1;i<outputFile.length();i++) 
    { 
     arr[i]=outputFile.valueOf(i); 

     PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into patent_uspto_tmp (pinv) values(?)"); 
      ps.setString(1,arr[i]); // set the param here with the some value 
      ps.executeUpdate(); 
      con.commit(); 
      con.close(); 
    } 
    } 
    catch(Exception e) 
    { 
     throw new RuntimeException(e);//System.out.println(e); 

    } 
} 
    } 

     error - null pointer exception 
+0

請告訴我的錯誤? – TheLostMind

+0

運行查詢後,它在mysql表中顯示爲空。如果我運行的代碼,我越來越像這樣 - 用戶連接爲 prerna

回答

0

你爲什麼要使用ResultSet用於插入查詢。 ResultSet從數據庫中提取數據。您必須使用statement.executeUpdate(sql)

Statement stmt=con.createStatement(); 
System.out.println("Inserting records into the table..."); 
stmt = conn.createStatement(); 
String sql = "INSERT INTO table" + 
        "VALUES (100, 'Zara', 'Ali', 18)"; 
stmt.executeUpdate(sql); 

用於讀取文件,然後插入到db中。您可以逐行讀取文件並將其存儲到String arr[]中,然後將插入查詢中的值傳遞爲arr[i];

+0

這樣做後,我得到相同的輸出。 – prerna

+0

可否請您提供代碼 – prerna

+0

獲取空指針異常。 – prerna

0

您正在向動態參數傳遞動態參數,並且沒有爲該動態參數設置任何值。改爲使用預處理語句,並將動態值作爲參數傳遞給查詢。

1

嘗試使用PreparedStatementexecuteUpdate()最後commit()方法是這樣的:

PreparedStatement ps = con.prepareStatement("insert into patent_uspto_tmp (pinv) values(?)"); 
    ps.setString(1, "value");// set the param here with the some value 
    ps.executeUpdate(); 
    con.commit(); 
+0

獲取輸出類似於 - 用戶連接爲 prerna

+0

獲得空指針異常。 – prerna

相關問題