Execute an SQL Script in JDBC

Reply

Join Date: Mar 2008
Posts: 21
Reputation: theausum has a little shameless behaviour in the past 
Solved Threads: 1
theausum theausum is offline Offline
Newbie Poster

Execute an SQL Script in JDBC

 
0
  #1
Oct 28th, 2008
Code to Execute an SQL Script in JDBC.
The SQL Script should have comments starting with - or -- only on new lines and each command should end with a ; .

Reading a sql file and putting all of it in a string variable and feeding to the execute command would result in an exception. All instructions must be executed individually. A proper sql script should have all instructions starting on a newline and all comments on a newline. Start with an empty string. Start reading the lines ; if a line has a - as the first character then continue else add it to the query string. Now if the last character of the query string is a ; then a command is complete so execute the query and make the query string empty and loop up. Thats it

Executing an sql script in jdbc with the following code should work ...
  1. //Now read line bye line
  2. String thisLine, sqlQuery;
  3. try {
  4. sqlQuery = "";
  5. while ((thisLine = d.readLine()) != null)
  6. {
  7. //Skip comments and empty lines
  8. if(thisLine.length() > 0 && thisLine.charAt(0) == '-' || thisLine.length() == 0 )
  9. continue;
  10. sqlQuery = sqlQuery + " " + thisLine;
  11. //If one command complete
  12. if(sqlQuery.charAt(sqlQuery.length() - 1) == ';') {
  13. sqlQuery = sqlQuery.replace(';' , ' '); //Remove the ; since jdbc complains
  14. try {
  15. stmt.execute(sqlQuery);
  16. }
  17. catch(SQLException ex) {
  18. JOptionPane.showMessageDialog(null, "Error Creating the SQL Database : " + ex.getMessage());
  19. }
  20. catch(Exception ex) {
  21. JOptionPane.showMessageDialog(null, "Error Creating the SQL Database : " + ex.getMessage());
  22. }
  23. sqlQuery = "";
  24. }
  25. }
  26. }
  27. catch(IOException ex) {
  28. }
  29. catch(Exception ex) {
  30. JOptionPane.showMessageDialog(null, "Error Creating the SQL Database : " + ex.getMessage());
  31. }
where d could be BufferedReader and c could be a Statement object.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC