开发者

How does JDBC URL properties work

开发者 https://www.devze.com 2023-02-07 10:41 出处:网络
In my app architecture one URL points to one Company Datasource. So to solve having severalCompanies on the same database I want to explore the po开发者_运维问答ssibility of adding an extra parameter

In my app architecture one URL points to one Company Datasource. So to solve having several Companies on the same database I want to explore the po开发者_运维问答ssibility of adding an extra parameter to the JDBC Url.

Basically what I want to do is to do a connection with the following URL.

jdbc:sqlserver://192.168.128.2:1433;databaseName=businessesDB;companyId=25

I have test that the connection is not affected by adding that custom param to the jdbc URL. But my question is how do I access the companyId property on my app.

Can I retrieve the value of that property using the Connection object that I've gotten from the Datasource?


It looks like you are using the Microsoft SQL Server driver. Take a look at http://msdn.microsoft.com/en-us/library/ms378988.aspx, and you should be able to use the applicationName property to identify which business is using the connection. The advantage of doing it this way is that SQL Server profiling and logging tools will identify the business in the connection as well.

In order to programatically obtain the applicationName, or, in your case, the business, you can use java.sql.Driver.getPropertyInfo(url, properties).


I'm going to post how I solve it. But I still feel that there should be a much better solution that would work regardless of the actual database, since Mysql Jdbc URL separates their params like an http URL and SQL Server JDBC driver expects properties to be separated with the ; character. After all thats why JDBC exists at all.

Using the regex applied to the URL I get the param like so:

        String url = company.getJdbcUrl();

        Pattern p = Pattern.compile("companyId=(\\d+)");
        Matcher m = p.matcher(url);

        if (m.find()) {
            companyId = m.group(1);
            _logger.info("companyId found");
        } else {
            _logger.error("could not get companyId");
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消