使用Properties文件获取Error数据库

时间:2012-11-01 13:24:17

标签: java properties error-handling

我正在使用数据库的属性文件,这是mycode:

我已将我的database.prperties文件设置在直接src文件夹中。

这是我的代码(我在jsp页面中应用此代码):

Properties prop=new Properties();
InputStream inputStream=null;
try{
    inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties");
    prop.load(inputStream);
}
finally{
    if (inputStream != null) try { inputStream.close(); } catch (IOException ignore) {}
}

String driver=prop.getProperty("driver");
if (driver != null)  
{  
    System.setProperty("driver", driver);  
}
String url = prop.getProperty("url");
String username= prop.getProperty("username");
String password = prop.getProperty("password");

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,username,password); // Getting error at this line.
Statement stmt = con.createStatement();
String sql = "select * from info;";
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);

这是我的属性文件:

driver=com.mysql.jdbc.Driver  
url=jdbc:mysql://localhost/abc
username=crips 
password=drift 

但我在第java.sql.SQLException: Access denied for user 'root '@'localhost' (using password: YES)

时收到此错误Connection con = DriverManager.getConnection(url,username,password);

此背景下的任何输入都会受到赞赏。

1 个答案:

答案 0 :(得分:2)

java.sql.SQLException: Access denied for user 'crips'@'localhost'

这意味着未授予给定用户访问您尝试连接的数据库的权限。您需要使用MySQL管理员权限发出以下SQL命令:

GRANT ALL ON abc.* TO 'crips'@'localhost' IDENTIFIED BY 'drift';

请注意,用户名和密码区分大小写。

另请注意,这毕竟与读取属性文件无关。将用户名/密码/数据库作为硬编码字符串变量提供时,您会遇到完全相同的问题。