gpt4 book ai didi

java - Hibernate 连接字符串做 MS SQL Server 2008 数据库名称(带大括号)

转载 作者:行者123 更新时间:2023-12-01 18:01:47 29 4
gpt4 key购买 nike

我必须连接到数据库,该数据库的名称中包含大括号 - {}(谁能做到这一点?!)。因此,数据库名称类似于 Production{guid-part-123123-123123-abcd},当我尝试连接它时出现错误。

连接字符串是:

public synchronized static SessionFactory getSessionFactory(String dbName) {

String url = String.format("jdbc:sqlserver://someServer:1433;databaseName=%s", dbName); // what can I do to give proper database name?

return new Configuration().configure()
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
.setProperty("hibernate.default_schema", "dbo")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect")
.setProperty("hibernate.connection.username", "admin")
.setProperty("hibernate.connection.password", "admin")
.setProperty("hibernate.connection.url", url)
.buildSessionFactory();
}

如何构建正确的 url/连接字符串?与该服务器上其他数据库的连接可以正常工作,但如果数据库名称包含“{}”,则会失败。

最佳答案

终于我成功解决了这个问题,这很简单,但花了几天时间才弄清楚。检查一下:

public synchronized static SessionFactory getSessionFactory(String dbName) {

String url = "jdbc:sqlserver://someServer:1433"; // we should skip here database name

return new Configuration().configure()
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
.setProperty("hibernate.default_schema", "dbo")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect")
.setProperty("hibernate.connection.username", "admin")
.setProperty("hibernate.connection.password", "admin")
.setProperty("hibernate.connection.url", url) // url is parsed by DriverManager class
.setProperty("hibernate.connection.databaseName", dbName) // this property is not parsed but just used
.buildSessionFactory();
}

如您所见,要解决此问题,您需要将 dbName 作为属性传递,这意味着不会被解析。找到解决方案帮助我得到了这个答案:https://stackoverflow.com/a/53704163/1679995

关于java - Hibernate 连接字符串做 MS SQL Server 2008 数据库名称(带大括号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60615618/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com