我怎样才能将我的mysql数据库url,用户名和密码放在一个文件中,我如何访问它们以便在我的java代码中使用,而不是硬编码它们。我试过谷歌,但没有得到明确的方向mysql数据库网址,用户名和密码在文件中
1
A
回答
3
创建一个properties file。您可以通过the Properties
API加载它。
E.g. config.properties
:
url = jdbc:mysql://localhost:3306/dbname
username = foo
password = bar
然后,你可以加载和阅读如下(你把它夹在类路径后):
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
// ...
0
/**
* Function that connects to a DB and data fro connection is loaded from a properties file
* @param fileName
* @return the connection to DB or null if any problem
*/
public java.sql.Connection connect_to_database_from_properties(String fileName)
{
Properties prop = new Properties();
InputStream is;
try {
is = new FileInputStream(fileName);
prop.load(is);
String url=prop.getProperty("url");
String un=prop.getProperty("username");
String pass=prop.getProperty("password");
System.out.println("URL: "+url+" UN: "+un+" PASS: "+pass);
is.close();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conection =DriverManager.getConnection(url, un, pass);
return conection;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
相关问题
- 1. Java数据库用户名和密码
- 2. 在java中加密数据库用户名和密码?
- 3. 如何找出mysql数据库的密码和用户名?
- 4. 检查MySQL数据库的用户名和密码C#
- 5. 如何找出mysql数据库的用户名和密码
- 6. Mysql changin数据库的用户名和密码
- 7. 在ssrs2008中询问用户名和密码的网址?
- 8. mysql phpmyadmin数据库用户密码
- 9. 在CouchDB _user数据库中更改用户名和密码
- 10. 验证在asp.net数据库中的用户名和密码
- 11. PHP mySQL检查用户名和密码是否在数据库中
- 12. 用户名/密码数据库检查
- 13. 如何更改用户名,密码在mysql数据库软件中
- 14. 使用用户名和密码从java代码创建mysql数据库
- 15. 蜻蜓:加密数据库的密码和用户名
- 16. 将用户输入的用户名/密码与mysql数据库用户名/密码比较不起作用
- 17. JDBC MySQL;足够提供数据库名称和用户名/密码?
- 18. 检查SOAP数据库中的SOAP Header用户名和密码?
- 19. LoginForm:比较数据库中的用户名和密码
- 20. MVC - 我的数据库中的用户名和密码
- 21. 验证数据库中的用户名和密码
- 22. Delphi中的数据库用户名和密码?
- 23. 在将用户名和密码插入数据库时出错
- 24. 从数据库验证硬编码的密码和用户名
- 25. 输入数据(用户名和密码)
- 26. 使用用户名,密码和所有权限从PHP创建MySQL数据库
- 27. 使用数据库进行Java用户名和密码验证
- 28. 用户名和密码的数据库验证不起作用。
- 29. Sqlite3 - 使用用户名和密码创建数据库
- 30. 如何使PHP代码通过电子邮件发送给邮件用户名和密码在mysql数据库
你的意思是创建某种配置文件,为您的Java应用程序? – tadman 2012-03-12 18:57:42
是的。这是最好的套件此连接,否则现在我只能在代码中指定它们之后运行我的应用程序,这将在文件中更好地完成 – ken 2012-03-12 19:06:21