2016-02-16 89 views
0

我試圖設置一個mySQL連接器,我不確定發生了什麼問題。以下是錯誤:barebones mySQL java連接器問題

SQLException: No suitable driver found for jdbc:mysql://localhost/db?user=root&password= 

這是我的java:

//  ESTABLISH DRIVER INSTANCE 
    try { 
     // The newInstance() call is a work around for some 
     // broken Java implementations 

     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    } catch (Exception ex) { 
     // handle the error 
    } 


    //  ESTABLISH DB CONNECTION 
    try { 
     conn = DriverManager.getConnection("jdbc:mysql://localhost/db?" + 
           "user="+user+"&password="+pass); 

     // Do something with the Connection 
     // 
     // 

    } catch (SQLException ex) { 
     // handle any errors 
     System.out.println("SQLException: " + ex.getMessage()); 
     System.out.println("SQLState: " + ex.getSQLState()); 
     System.out.println("VendorError: " + ex.getErrorCode()); 
    } 

這裏是我的build.xml:

<project> 

<target name="run"> 

    <javac srcdir="." destdir="."> 

     <classpath> 
       <pathelement path="./mysql-connector-java-5.1.38i/mysql-connector-java-5.1.38-bin.jar"/> 
       <pathelement location="./DB_Test.class"/> 
     </classpath> 

    </javac> 

    <java classname="DB_Test"> 

      <classpath> 
       <pathelement path="./mysql-connector-java-5.1.38i/mysql-connector-java-5.1.38-bin.jar"/> 
       <pathelement location="."/> 
      </classpath> 

    </java> 

</target> 

</project> 

我認爲這個問題很可能是在構建。 XML,因爲我對螞蟻很不熟悉。我不確定這兩種「途徑」是否必要,或者其中任何一個是否有效。我想知道如果我需要爲這個罐子食用日食。

我也認爲我的連接URL語法可能存在問題。 「db」是連接的名字嗎?或架構?我的本地主機後需要端口號嗎?

+0

不能對全球的解決方案幫助,但對URL語法:「DB」是連接到數據庫,如果你不提供端口號,則默認爲3306(見https://開頭docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html)。 –

回答

0

我的問題是,我沒有正確的jar添加到類路徑。 我試過它的命令行,使用-cp參數,它工作。我發現this非常有幫助。

If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.

java -cp .;/path/to/mysql-connector.jar com.example.YourClass 

The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.

0

也許你可以把它改成

Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/XX","root","yourpassword" 
+0

我試過了,我仍然得到相同的錯誤 –