FileDocCategorySizeDatePackage
ResultsDecoratorSQL.javaAPI DocExample1790Thu Mar 25 20:39:34 GMT 2004None

ResultsDecoratorSQL

public class ResultsDecoratorSQL extends ResultsDecorator
Print an SQL ResultSet in SQL-import format. TODO: check all escaped characters needed! Test on PGSQL and DB2 at least...
version
$Id: ResultsDecoratorSQL.java,v 1.2 2004/03/26 02:39:33 ian Exp $

Fields Summary
Constructors Summary
ResultsDecoratorSQL(ResultsDecoratorPrinter out)

		super(out);
	
Methods Summary
java.lang.StringgetName()

		return "SQL";
	
public voidwrite(java.sql.ResultSet rs)

		ResultSetMetaData md = rs.getMetaData();
		// This assumes you're not using a Join!!
		String tableName = md.getTableName(1);
		int cols = md.getColumnCount();
		StringBuffer sb = new StringBuffer("insert into ").append(tableName).append("(");
		for (int i = 1; i <= cols; i++) {
			sb.append(md.getColumnName(i));
			if (i != cols) {
				sb.append(", ");
			}
		}
		sb.append(") values (");
		String insertCommand = sb.toString();
		while (rs.next()) {
			println(insertCommand);		
			for (int i = 1; i <= cols; i++) {
				String tmp = rs.getString(i);
				if (rs.wasNull()) {
					print("null");
				} else {
					int type = md.getColumnType(i);
					// Don't quote numeric types; quote all others for now.
					switch (type) {
						case Types.BIGINT:
						case Types.DECIMAL:
						case Types.DOUBLE:
						case Types.FLOAT:
						case Types.INTEGER:
							print(tmp);
							break;
						default:	
							tmp = tmp.replaceAll("'", "''");
							print("'" + tmp + "'");
					}
				}
				if (i != cols) {
					print( ", ");
				}
			}
			println(");");
		}
	
voidwrite(int rowCount)

		println("RowCount: " + rowCount);