连接时出现MySQL JDBC错误

时间:2013-10-08 20:19:08

标签: java mysql jdbc

我正在尝试建立与远程mysql db的连接。我已将jar连接器放到war/WEB-INF/lib文件夹并添加了一个库(构建路径)。

我仍然收到此错误:

java.sql.SQLException: No suitable driver found for jdbc:sql4.freemysqlhosting.net
    at java.sql.DriverManager.getConnection(Unknown Source)

以下是完整代码:

/**
 * 
 */
package com.infograph.dbconnection;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Vlad
 *
 */
public class DBConnection 
{
    /**
     * 
     */
    public DBConnection() 
    {
        try 
        {
            Class.forName("com.mysql.jdbc.Driver");
        } 
        catch (ClassNotFoundException e) 
        {
            System.out.println("Where is your MySQL JDBC Driver?");
            e.printStackTrace();
            return;
        }

        System.out.println("MySQL JDBC Driver Registered!");
        Connection connection = null;

        try 
        {
            connection = DriverManager.getConnection("jdbc:sql4.freemysqlhosting.net","user", "pass");

        } 
        catch (SQLException e1) 
        {
            System.out.println("Connection Failed! Check output console");
            e1.printStackTrace();
            return;
        }

        if (connection != null) 
        {
            System.out.println("You made it, take control your database now!");
        } 
        else 
        {
            System.out.println("Failed to make connection!");
        }
    }
}

问题是什么? 10倍!

2 个答案:

答案 0 :(得分:1)

我认为您打算使用的是

connection = DriverManager.getConnection("jdbc:mysql://sql4.freemysqlhosting.net","user", "pass");

您可能需要添加端口号和架构名称。

您提供的网址jdbc:sql4.freemysqlhosting.net无效,或者至少看起来不像。

答案 1 :(得分:1)

您的连接URL必须采用jdbc:mysql:// hostname:port / schema格式,以便DriverManager确定要使用的驱动程序。 以下是对此的更多信息: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html