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.
Class.forName()
with modern JDBC drivers, since JDBC can now use the theServiceLoader
system for finding drivers (more info here). You will still find theforName()
call in many tutorials since it doesn't break anything. – Joachim Sauer