DBUnit有没有办法自动创建表?

编程入门 行业动态 更新时间:2024-10-28 00:24:30
本文介绍了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有没有办法自动创建表?

本文发布于:2023-11-03 14:27:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555364.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   DBUnit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!