我们如何轻松导入/导出dbunit可以采用以下格式的数据库数据?
<dataset>
<tablea cola="" colb="" />
<tableb colc="" cold="" />
</dataset>
我想找到一种方法从数据库导出现有数据以进行单元测试。
答案 0 :(得分:14)
蓝色,这将允许您以您想要的格式导出数据。
public class DatabaseExportSample {
public static void main(String[] args) throws Exception {
// database connection
Class driverClass = Class.forName("org.hsqldb.jdbcDriver");
Connection jdbcConnection = DriverManager.getConnection(
"jdbc:hsqldb:sample", "sa", "");
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
// partial database export
QueryDataSet partialDataSet = new QueryDataSet(connection);
partialDataSet.addTable("FOO", "SELECT * FROM TABLE WHERE COL='VALUE'");
partialDataSet.addTable("BAR");
FlatXmlDataSet.write(partialDataSet, new FileOutputStream("partial.xml"));
// full database export
IDataSet fullDataSet = connection.createDataSet();
FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));
// dependent tables database export: export table X and all tables that
// have a PK which is a FK on X, in the right order for insertion
String[] depTableNames =
TablesDependencyHelper.getAllDependentTables( connection, "X" );
IDataSet depDataSet = connection.createDataSet( depTableNames );
FlatXmlDataSet.write(depDataSet, new FileOutputStream("dependents.xml"));
}
}
答案 1 :(得分:6)
导出已经回答了。
要完成答案,您可以将数据集导入数据库。
connection
的类型为IDatabaseConnection
。
Mark Robinson先前的回答(出口)包含如何创建数据库连接的代码。
FlatXmlDataSet dataSet = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(new FileInputStream("dataset.xml"))));
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);