DBUnit 有没有办法自动创建表?
2022-09-01 23:35:32
我刚刚意识到DBUnit不会自己创建表(请参阅如何使用DBUnit与普通JDBC和HSQLDB进行测试而不面对NoSuchTableException?)。
DBUnit 有没有办法从数据集或 dtd 自动创建表?
编辑:对于像 HSQLDB 这样的内存中数据库的简单测试,可以使用一种粗略的方法来自动创建表:
private void createHsqldbTables(IDataSet dataSet, Connection connection) throws DataSetException, SQLException {
String[] tableNames = dataSet.getTableNames();
String sql = "";
for (String tableName : tableNames) {
ITable table = dataSet.getTable(tableName);
ITableMetaData metadata = table.getTableMetaData();
Column[] columns = metadata.getColumns();
sql += "create table " + tableName + "( ";
boolean first = true;
for (Column column : columns) {
if (!first) {
sql += ", ";
}
String columnName = column.getColumnName();
String type = resolveType((String) table.getValue(0, columnName));
sql += columnName + " " + type;
if (first) {
sql += " primary key";
first = false;
}
}
sql += "); ";
}
PreparedStatement pp = connection.prepareStatement(sql);
pp.executeUpdate();
}
private String resolveType(String str) {
try {
if (new Double(str).toString().equals(str)) {
return "double";
}
if (new Integer(str).toString().equals(str)) {
return "int";
}
} catch (Exception e) {}
return "varchar";
}