SuperX-Kernmodul
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

83 lines
3.2 KiB

package de.memtext.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Additional procedures for HSQLDB
* make sure that this class in the classpath.
* To constantly add it to hsql, go to the directory where your hsqldb.jar is located
* Call jar -xf hsqlAddOn.jar
* jar -uf hsqldb.jar org/hsqldb/Library2.class
* Delete the directory org.
*
* Open your Database in Database Manager and execute
* the following commands once:
* GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC and
* CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom"
*/
public class Library2 {
private Library2() {
super();
}
/**
* Fills regular tables with values from a CSV-file.
* Similar to Postgres COPY FROM command.
*
* If you want to fill your table TEST with data from test.csv
* make sure that this class in the classpath and that
* GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC and
* CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom"
* has been called in your database at some point.
* * Then execute
* COPYFROM("TEST","test.csv",null)
*
* if your not using , but | as a field separator
COPYFROM("TEST","test.csv","fs=|")
*
* @param con - Connection is automatically handed over by HSQL
* @param table - the name of the table that is to be filled
* if your table isn't found capital letters may be required
* @param file - the filename of the CSV-file
* @param options - you can specify options separated by ;
* which are described in the text table documentation e.g.
* fs=| to use pipe instead of default comma as field separator or
* or
* fs=|;vs=.;lvs=~" varchar separator, longvarchar separator
* ignore_first=true; ignore first line
* all_quoted=true or
* encoding=UTF-8 if you don't have ASCII
* @throws SQLException
*/
public static void copyFrom(Connection con, String table, String file, String options) throws SQLException {
StringBuffer buf = new StringBuffer("create text table TMP_SOURCE_" + table + " (");
ResultSet rs = con.getMetaData().getColumns(null, null, table, null);
String colname, coltype;
boolean tableFound = false;
while (rs.next()) {
tableFound = true;
colname = rs.getObject(4).toString();
coltype = rs.getObject(6).toString();
buf.append(colname + " " + coltype + ",");
}
rs.close();
if (!tableFound) throw new IllegalArgumentException("Copy from failed - table " + table + " not found");
buf.deleteCharAt(buf.lastIndexOf(","));
buf.append("); SET TABLE TMP_SOURCE_" + table + " SOURCE \"" + file);
if (options != null) buf.append(";" + options);
buf.append("\";");
buf.append("insert into " + table + " select * from TMP_SOURCE_" + table);
Statement stmt = con.createStatement();
try {
stmt.execute(buf.toString());
} finally {
stmt.execute("drop table TMP_SOURCE_" + table + " IF EXISTS");
}
}
}