2016-03-02 165 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

相关问题