【问题标题】:Escaping reserved database keywords with spring-test-dbunit使用 spring-test-dbunit 转义保留的数据库关键字
【发布时间】:2013-05-28 19:50:08
【问题描述】:

如何使用 Spring-test-dbunit framework 转义 SQL Server 关键字?

在我的@DatabaseSetup("sampleData.xml") 文件中,我有一个名为File 的表,它是SQL Server 中的保留关键字。为了使查询在 SQL Server 上成功运行,保留关键字需要用方括号 ([File]) 封装。

Expoting Dataset to a xml file giving error in DBunit,我看到这可以通过设置模式转义配置在 dbunit 中完成。使用 Spring-test-dbunit 时,我不知道在哪里或如何放置此配置。

在使用提供的 xml 提要将测试数据插入数据库时​​,我在哪里/如何告诉 spring-test-dbunit 框架正确转义数据库关键字?

如果您想查看代码,请告诉我应该发布哪些摘录,我很乐意这样做。

【问题讨论】:

    标签: java spring junit dbunit spring-test-dbunit


    【解决方案1】:

    我想,这可能对你有帮助

    public class DatabaseExport
    {
        public static void main(String[] args) throws Exception
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
            Connection jdbcConn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=def_config","dbuser","dbpasswd");
            IDatabaseConnection iconn = new DatabaseConnection( jdbcConn );
            iconn.getConfig().setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN , "[?]");
            IDataSet fullDataSet = iconn.createDataSet();
            FlatXmlDataSet.write(fullDataSet, new FileOutputStream("X:/fullDataSet.xml"));
        }
    }
    

    【讨论】:

    • 由于我使用的是Spring框架,所以没有使用上面的数据库设置代码。相反,我依靠 Spring 来设置我的数据库连接,并在 XML 配置中提供连接详细信息。问题是我不知道 howif 我可以在 XML 配置中指定此配置:DatabaseConfig.PROPERTY_ESCAPE_PATTERN , "[?]"
    • @nmc 您是否查看了 [spring-test-dbunit] (springtestdbunit.github.io/spring-test-dbunit) 中的“DbUnitTestExecutionListener 的高级配置”或“DbUnitRule 的高级配置”或“自定义 IDatabaseConnections”部分?也许它可以帮助您配置连接。
    • @Hippoom 我认为“自定义 IDatabaseConnections”正是我想要的。如果您想发布完整的答案,我很乐意接受。我目前无法对其进行测试,因为我已通过表格重命名以解决此问题。
    • @nmc 谢谢但不要打扰,我只给出了一半的答案,它的灵感来自 sreeprasad-govindankutty。所以我建议编辑这个答案然后接受这个:)
    • 你可以像这样创建一个testContext.xml stackoverflow.com/questions/22796147/…
    【解决方案2】:

    要使用 spring-test-dbunit 执行此操作,您需要遵循其文档页面上的“自定义 IDatabaseConnections”部分:https://springtestdbunit.github.io/spring-test-dbunit/

    对于 Java Config 变体(并作为备份参考),请参阅此 StackOverflow 问题的答案:Spring Test DBunit Warning

    在您的情况下,使用dbUnitDatabaseConfig bean,将escapePattern 属性设置为"[?]"。如:

    <bean id="dbUnitDatabaseConfig" class="com.github.springtestdbunit.bean.DatabaseConfigBean">
        <property name="escapePattern" value="[?]"/>
    </bean>
    

    旁注,如果在测试运行时使用 JPA/Hibernate 生成单元测试模式,则还需要为 Hibernate 进行转义。请参阅此答案:https://stackoverflow.com/a/3463189/1034436

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2022-02-26
      • 2015-03-27
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多