Cannot find the JDBC driver
I have a simple JDBC code.
static Connection c;
static PreparedStatement ps;
public static void initializeDB() throws IOException, ClassNotFoundException, SQLException {
Properties prop = new Properties();
prop.load(new FileInputStream("dbconn.properties"));
String connurl = prop.getProperty("connurl");
String driver = prop.getProperty("driver");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(driver); //prints "com.mysql.jdbc.Driver"
Class.forName(driver);
c = DriverManager.getConnection(connurl, username, password);
But I'm getting
java.lang.ClassNotFoundException: "com.mysql.jdbc.Driver" at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at testapp.DBUpdater.initializeDB(Testapp.java:71) at testapp.Testapp.main(Testapp.java:38)
The property values are perfectly accessed as seen from the print statement. When I replace the variables with the string values directly it works fine!!
When should I use
prop.load(new FileInputStream(System.getProperty("dbconn.properties")));
When I viewed the Driver class from the mysql-connector jar file, I was expecting to see some static code but didn't find anything.
It looks like the string has value "com.mysql.jdbc.Driver"
(note the double quotes) instead of com.mysql.jdbc.Driver
.
Remove those quotes and it should work.
Try to trim the values of the properties.
I would have load the properties in a static way.
I didn't understand why you had a look within this JAR...
Example:
class Database {
private final static Properties properties;
private static Connection c;
private static PreparedStatement ps;
static {
properties = new Properties();
properties.load(new FileInputStream("dbconn.properties"));
}
public static void init() {
String connurl = properties.getProperty("connurl").trim();
String driver = properties.getProperty("driver").trim();
String username = properties.getProperty("username").trim();
String password = properties.getProperty("password").trim();
Class.forName(driver);
c = DriverManager.getConnection(connurl, username, password);
}
}
链接地址: http://www.djcxy.com/p/33048.html
上一篇: 在Apache HTTP客户端的例外
下一篇: 找不到JDBC驱动程序