patternjavaMinor
Execute multiple query from a text file
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:
Plus it lacks of proper exception/error handling and resource closing as others mentioned in the comments.
- Separate the GUI code from the logic.
- If you stay with your current mixed code fail fast. If
connisnullthere no sense to open the file or ask the user to choose one.
JFileChooser.getSelectedFile()returns aFileinstance, pass it toFileInputStreamdirectly, don't concatenate strings.Filecontains the absolute path.
- It's a good practice to pass a
Charset(or"UTF-8") the the constructor of theInputStreamReader. The default could vary from system to system.
- The
DataInputStreamlooks unnecessary. You can pass theFileInputStreamto theInputStreamReaderdirectly.
- 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.