FileDocCategorySizeDatePackage
SQLRunner.javaAPI DocExample2882Tue Dec 25 20:04:06 GMT 2001None

SQLRunner

public class SQLRunner extends Object
Class to run an SQL script. Command line interface hard-codes sample driver and dburl, expects script file name in argv[0]. Can be used from within servlet, etc.
author
Ian Darwin, ian@darwinsys.com

Fields Summary
protected String
db_driver
The database driver
protected String
db_url
The database URL.
protected String
user
protected String
password
protected Connection
conn
Database connection
protected Statement
stmt
SQL Statement
Constructors Summary
public SQLRunner(String driver, String dbUrl, String user, String password)

		db_driver = driver;
		db_url = dbUrl;
		this.user = user;
		this.password = password;

		// Load the database driver
		Class.forName(db_driver);

		conn = DriverManager.getConnection(
			db_url, user, password);

		stmt = conn.createStatement();
	
Methods Summary
public voidclose()

		stmt.close();
		conn.close();
	
public static java.lang.StringgetStatement(java.io.BufferedReader is)
Extract one statement from the given Reader. Ignore comments and null lines.

		String ret="";
		String line;
		boolean found = false;
		while ((line = is.readLine()) != null) {
			if (line == null || line.length() == 0) {
				continue;
			}
			if (!line.startsWith("#")) {
				ret += ' " + line;
				found = true;
			}
			if (line.endsWith(";")) {
				ret = ret.substring(0, ret.length());
				return ret;
			}
		}
		return null;
	
public static voidmain(java.lang.String[] args)

		String DB_DRIVER;
		// DB_DRIVER = "jdbc.idbDriver";
		DB_DRIVER = "org.hsqldb.jdbcDriver";
		String DB_URL;
		//DB_URL = "jdbc:idb:orders.prp";
		DB_URL = "jdbc:hsqldb:ordersdb";

		try {
			SQLRunner prog = new SQLRunner(DB_DRIVER, DB_URL,
				"sa", "");
			prog.runScript(args[0]);
			prog.close();
		} catch (Exception ex) {
			System.out.println("** ERROR **");
			System.out.println(ex.toString());
			System.exit(1);
		}
	
public voidrunScript(java.lang.String scriptFile)
Run one script file. Called from cmd line main or from user code.


		BufferedReader is;

		// Load the script file first, it's the most likely error
		is = new BufferedReader(new FileReader(scriptFile));

		String str;
		int i = 0;
		System.out.println("SQLRunner: ready.");
		while ((str = getStatement(is)) != null) {
			runStatement(str);
		}
	
public voidrunStatement(java.lang.String str)
Run one Statement as an Update. Called from runScript or from user code.

		System.out.println("Executing update : <<" + str + ">>");
		System.out.flush();
		int ret = stmt.executeUpdate(str);
		System.out.println("Return code: " + ret);
		System.out.println();