【问题标题】:Question about build.properties关于 build.properties 的问题
【发布时间】:2011-08-17 23:27:02
【问题描述】:

我正在编写一个使用 JDBC 并连接到数据库并进行一些编辑/删除的程序。我需要将 URL、用户名和密码字段放入 build.properties 文件中,但我不确定它的外观或如何真正让它工作。 (我对此完全陌生,还没有找到任何与此相关的资源)

例如,在我的代码中,我有这样的内容:

String username = "something"
String password = "something"
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ENABLE=BROKEN)" + "(FAILOVER=ON)(LOAD_BALANCE=ON)(ADDRESS=(PROTOCOL=TCP) ... etc", username, password);

我想把它放在 build.properties 中,让我的代码使用这些属性而不是我现在的做法来创建连接。 任何帮助将不胜感激!

【问题讨论】:

    标签: sql jdbc build connection


    【解决方案1】:

    类似这样的:

    首先,创建database.properties:

    database.url = jdbc:mysql://host:port/database
    database.driver = com.mysql.jdbc.Driver
    database.username = username
    database.password = password
    

    其次,将 database.properties 放入您的 CLASSPATH 中。

    代码如下所示:

    InputStream is = this.getClass().getClassLoader().getResourceAsStream("database.properties");
    Properties dbProperties = Properties.load(is);    
    Class.forName(dbProperties.getProperty("database.driver"));
    Connection connection =     DriverManager.createConnection(dbProperties.getProperty("database.url"));
    

    我没有编译它,我不确定语法是否 100% 正确,但这说明了主要思想。

    【讨论】:

    • 哦,我明白了,这很有道理,谢谢。您介意解释一下如何在构建属性中指定这些属性吗?
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 2021-11-29
    • 2011-09-22
    • 2018-05-23
    • 2011-11-16
    • 2021-03-27
    • 2017-01-27
    • 2011-10-31
    相关资源
    最近更新 更多