public class JDBC_Test { // 创建静态全局变量 public Connection conn=null; public Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://127.0.0.1:3306/test"; String user="root"; String password="gehaishuai"; conn=DriverManager.getConnection(url,user,password); if(conn!=null){ System.out.println("数据库连接成功"); } }catch (Exception e){ e.printStackTrace(); } return conn; } public static void main(String[]args){ JDBC_Test getConn= new JDBC_Test(); getConn.getConnection(); } }
抛出的异常如下: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at chp07.JDBC_Test.getConnection(JDBC_Test.java:11) at chp07.JDBC_Test.main(JDBC_Test.java:26)