我正在尝试使用Java连接mysql。 我正在使用db.properties文件来获取连接详细信息。
我是一个使用db.properties文件的新人。我的代码有什么问题??
如下所示
#mysql DB properties
#DB_DRIVER_CLASS=com.mysql.jdbc.Driver
#DB_URL=jdbc:mysql://localhost:8080/ci_intro
#DB_USERNAME=root
#DB_PASSWORD=
我的Java类文件是
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCExample {
public static void main(String[] argv) throws IOException,
ClassNotFoundException, SQLException {
System.out
.println("-------- MySQL JDBC Connection Testing ------------");
Properties props = new Properties();
FileInputStream in = new FileInputStream("db.properties");
props.load(in);
in.close();
String driver = props.getProperty("DB_DRIVER_CLASS");
if (driver != null) {
Class.forName(driver);
}
String url = props.getProperty("DB_URL");
String username = props.getProperty("DB_USERNAME");
String password = props.getProperty("DB_PASSWORD");
Connection con = DriverManager.getConnection(url, username, password);
if (con != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
我收到以下错误
-------- MySQL JDBC Connection Testing ------------
Exception in thread "main" java.sql.SQLException: The url cannot be null
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.avn.notificationengine.JDBCExample.main(JDBCExample.java:33)
答案 0 :(得分:2)
删除#
文件中的“*.properties
”。 “#
”之后的所有内容都是评论。您的*.properties
应为:
#mysql DB properties
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:8080/ci_intro
DB_USERNAME=root
DB_PASSWORD=