import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//This class is for testing connection with mysql database
class JDBCTest {
// path to database is stored in string url
private static final String url = "jdbc:mysql://localhost";
// username is stored in string root
private static final String user = "root"; //username
// password is stored in string password
private static final String password = "swapnil";//password
public static void main(String args[]) {
try {
//i have stored driver in c:\javap\
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
} catch (Exception e) {
System.out.println("hi");
e.printStackTrace();
}
}
}
每当我尝试运行此程序时,我都会遇到例外情况
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
mysql-connector-java-5.1.22-bin in jdk/jre/lib/ext
我还设置了CLASSPATH
环境变量,但没有任何方法可以帮助我
答案 0 :(得分:3)
首先,你不应该把任何东西放在JDK的jre / lib / ext目录下。
相反,在启动应用程序时使用-cp
选项,并确保在类路径中包含驱动程序的 jar (而不是bin目录):
java -cp mysql-xx.jar;... com.foo.bar.JDBCTest
答案 1 :(得分:1)
网址使用不完整:
private static final String url = "jdbc:mysql://localhost:3306/databasename";
同样@JB Nizet提到不要把jars放在jdk的lib中。