Click here to Skip to main content
15,886,574 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
code for database records are added when the program runs, required however is the code which reads from text file and adds records on database

package Rdbms;

import java.sql.*;  
import java.io.*;  

class javardbms
{  
public static void main(String args[])throws Exception{  
Class.forName("org.apache.derby.jdbc.ClientDriver");  
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Oracle;create=true;user=Android;password=java");  
  
PreparedStatement y=con.prepareStatement("insert into GOOD values(45,'Who')");  
  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
do{   
int i=y.executeUpdate();  
System.out.println(i+" records affected");    
System.out.println("Do you want to continue: y/n");  
String s=br.readLine();  
if(s.startsWith("n")){  
break;  
}  
}while(true);    
con.close();  
}}  


What I have tried:

changed the code , used string file path
Posted
Updated 7-Feb-18 2:12am
v2
Comments
Richard MacCutchan 30-Jan-18 10:09am    
You are using a BufferedReader on System.in, which is the console. If you want to read data from a text file you need to change the reader to read from the file in question.

1 solution

Java
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertTextFileToOracle {

  public static Connection getConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:oracle";
    String username = "username";
    String password = "password";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String[] args)throws Exception {
    String id = "001";
    String fileName = "fileName.txt";
    
    FileInputStream fis = null;
    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
      conn = getConnection();
      conn.setAutoCommit(false);
      File file = new File(fileName);
      fis = new FileInputStream(file);
      pstmt = conn.prepareStatement("insert into DataFiles(id, fileName, fileBody) values (?, ?, ?)");
      pstmt.setString(1, id);
      pstmt.setString(2, fileName);
      pstmt.setAsciiStream(3, fis, (int) file.length());
      pstmt.executeUpdate();
      conn.commit();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      pstmt.close();
      fis.close();
      conn.close();
    }
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900