我需要帮助来编写将类(表示数据库表)的内容转储到 MS Access 中的新数据库表。我的代码如下:
public void dumpDB() throws IOException, Exception {
// for each table
for (String tableName : this.DB.getTablesNames()) {
System.out.println(tableName);
int nColumns = 0;
ModelDatabaseTable table = this.DB.getTable(tableName);
// create a tablebuilder
TableBuilder DBTableBuilder = new TableBuilder(tableName);
// get datatypes of columns
Map<String, DataType> columns = table.getColumns();
// for each column
for (String columnName : columns.keySet()) {
System.out.println(columnName);
// get its datatype
DataType dt = columns.get(columnName);
// create a column with correspondent datatype and max length and add it
// to the table builder
ColumnBuilder cb = new ColumnBuilder(columnName).setType(dt).setMaxLength();
DBTableBuilder.addColumn(cb);
nColumns += 1;
}
// if table has columns
if (nColumns > 0) {
// save it to the actual database: Exception rises here
Table DBTable = DBTableBuilder.toTable(this.DBConnection);
// copy all table's rows
for (ModelDatabaseRow row : table.getRows()) {
List<String> values = new ArrayList<String>();
for (String columnName : columns.keySet()) {
String columnValue = row.getColumn(columnName);
values.add(columnValue);
}
DBTable.addRow(values.toArray());
}
}
}
}
当我尝试将表保存到实际数据库时,出现异常:
java.lang.IllegalArgumentException: invalid fixed length size
at com.healthmarketscience.jackcess.ColumnBuilder.validate(ColumnBuilder.java:361)
at com.healthmarketscience.jackcess.impl.TableCreator.validate(TableCreator.java:207)
at com.healthmarketscience.jackcess.impl.TableCreator.createTable(TableCreator.java:130)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.createTable(DatabaseImpl.java:954)
at com.healthmarketscience.jackcess.TableBuilder.toTable(TableBuilder.java:223)
at modelDatabase.AccessModelDatabaseBuilder.dumpDB(AccessModelDatabaseBuilder.java:153)
at modelDatabase.AccessModelDatabaseBuilder.main(AccessModelDatabaseBuilder.java:37)
数据类型在使用我正在编写的同一数据库之前保存(我基本上是在更新数据库),使用以下代码:
for (Column column : DBTable.getColumns()) {
table.addColumn(column.getName(), column.getType(), "");
}
我做错了什么?
从 Jackcess 论坛线程中,解决方案是包装对setMaxLength()
方法的调用:
if(dt.isVariableLength()) {
cb.setMaxLength();
}