连接错误Java MySQL

时间:2012-08-15 06:03:48

标签: java mysql jdbc

我已经安装了MySQL Connector 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

3 个答案:

答案 0 :(得分:3)

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

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) { }
       }
    }

答案 1 :(得分:0)

你可以试试这个:

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

而不是

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

答案 2 :(得分:0)

在程序中插入此代码以检查类路径 的System.out.println(System.getProperty( “java.class.path”));