2

我已经安装了 MySQL 连接器 J、WAMP [MySQL 附带的] 和 Java JDK 1.7,但它总是通过异常com.mysql.jdbc.Driver

编码

import java.sql.*;

public class sou
{
   public static void main (String[] args)
   {
       Connection conn = null;
       try
       {
           String userName = "root";
           String password = "";
           String url = "jdbc:mysql://localhost/cms";
           Class.forName ("com.mysql.jdbc.Driver").newInstance ();
           conn = DriverManager.getConnection (url, userName, password);
            conn.close();
       }
       catch (Exception e)
       {
           System.err.println (e.getMessage());
       }
   }
}

我将其编译为

 C:\Users\Sou\Desktop>javac -cp "D:\Program Files\MySQL\Connector J 5.1.20.0\mysql-connector-java-5.1.20-bin.jar" sou.java
4

3 回答 3

3

mysql-connector-java-5.1.20-bin.jar在编译和运行应用程序时,您必须包含在您的 CLASSPATH 中。

C:\Users\Sou\Desktop>javac -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
                                    mysql-connector-java-5.1.20-bin.jar" sou.java


C:\Users\Sou\Desktop>java -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
                                    mysql-connector-java-5.1.20-bin.jar" sou

并且无需调用 newInstance() 方法。

   Connection conn = null;
   try{
       String userName = "root";
       String password = "";
       String url = "jdbc:mysql://localhost/cms";
       Class.forName ("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection (url, userName, password);
   }
   catch (Exception e){
       System.err.println (e.getMessage());
   }finally{
       if(conn!=null){
          try{
             conn.close();
          }catch(Exception ex) { }
       }
    }
于 2012-08-15T06:08:31.347 回答
0

你可以试试这个:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

代替

Class.forName ("com.mysql.jdbc.Driver").newInstance ();
于 2012-08-15T06:12:04.380 回答
0

将此代码插入您的程序以检查类路径 System.out.println(System.getProperty("java.class.path"));

于 2013-04-10T13:31:05.323 回答