DBUnit有没有办法自动创建表? [英] Is there any way for DBUnit to automatically create tables?

查看:370
本文介绍了DBUnit有没有办法自动创建表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到DBUnit本身并不创建表(请参阅如何使用简单的JDBC和HSQLDB进行DBUnit测试,而不会面临NoSuchTableException ?)。

I just realized that DBUnit doesn't create tables by itself (see How do I test with DBUnit with plain JDBC and HSQLDB without facing a NoSuchTableException?).

DBUnit有没有办法自动从数据集或dtd创建表?

Is there any way for DBUnit to automatically create tables from a dataset or dtd?

编辑:对于像HSQLDB这样的内存数据库的简单测试,可以使用粗略的方法自动创建表:

For simple testing of an in-memory database like HSQLDB, a crude approach can be used to automatically create tables:

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";
}


推荐答案

作为您链接的答案指出,dbunit xml文件包含数据,但不包括列类型。

Not really. As the answer you linked points out, the dbunit xml files contain data, but not column types.

您真的不想这样做; / em>您可能会冒险用测试工件污染您的数据库,从而打开生产代码意外依赖测试过程创建的表的可能性。

And you really don't want to do this; you risk polluting your database with test artifacts, opening up the possibility that production code will accidentally rely on tables created by the test process.

需要这么做建议您没有充分定义和编写数据库创建和维护过程。

Needing to do this strongly suggests you don't have your db creation and maintenance process adequately defined and scripted.

这篇关于DBUnit有没有办法自动创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆