2016-02-16 48 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

我试过了,我仍然得到相同的错误 –