HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Execute multiple query from a text file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetextquerymultiplefromexecute

Problem

I am just wondering if this is a correct way to execute multiple query from a text file.

Connection conn = Utility.getConnection();
Statement stmt = null;
try{
    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showOpenDialog(chooser);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       String fileName=chooser.getCurrentDirectory().toString()+File.separator+chooser.getSelectedFile().getName();
       FileInputStream fstream = new FileInputStream(fileName);
       DataInputStream in = new DataInputStream(fstream);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));
       String strLine;
       if(conn != null)
           stmt = conn.createStatement();
       while ((strLine = br.readLine()) != null)   {
           if(stmt !=null){
               int rc=stmt.executeUpdate(strLine);
               if(rc == 0)
                   System.out.println("executing:  "+strLine);
           }                   
       }
       stmt.close();
       conn.close();
       in.close();
    }
}catch (Exception e){
    e.printStackTrace();
}

Solution

Some ideas:

  • Separate the GUI code from the logic.



  • If you stay with your current mixed code fail fast. If conn is null there no sense to open the file or ask the user to choose one.



  • JFileChooser.getSelectedFile() returns a File instance, pass it to FileInputStream directly, don't concatenate strings. File contains the absolute path.



  • It's a good practice to pass a Charset (or "UTF-8") the the constructor of the InputStreamReader. The default could vary from system to system.



  • The DataInputStream looks unnecessary. You can pass the FileInputStream to the InputStreamReader directly.



  • Consider using Guava's readLines.



  • Maybe you want to report all executed queries, so the if (rc == 0) condition is unnecessary.



Plus it lacks of proper exception/error handling and resource closing as others mentioned in the comments.

Context

StackExchange Code Review Q#5558, answer score: 4

Revisions (0)

No revisions yet.