如何解决异常java.sql.SQLException:找不到合适的驱动程序?

时间:2014-09-08 19:52:21

标签: java mysql jdbc

连接到MYSQL时出现以下错误

java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost/chatdb

这是我的代码:

public class Connect(){ 
    Connection conn;
    public Connection getConnect()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection
                       ("jdbc:sqlserver://localhost/chatdb","myserver","pass");
            System.out.println("Database connection established");
        }
        catch(Exception e){System.out.println(e);}
    }
}

我不知道是什么问题。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

你的MySQL驱动程序(.jar)在类路径上不是
此外,您的连接字符串错误,当您想连接到MySQL时

应该看起来像:
jdbc:mysql://[host][:port]/[database][?property1][=value1]

例如:

jdbc:mysql://localhost/test?user=monty&password=greatsqldb

但是在您的连接字符串中,您已经要求" SQL-Server的驱动程序(jdbc:sqlserver)。

修改
你可以看看这个一步一步的tuturial: http://www.vogella.com/tutorials/MySQLJava/article.html

答案 1 :(得分:1)

使用以下方法获取连接:

getConnection("jdbc:mysql://localhost:3306/dbName","username", "password");//presuming that mysql server is running on port 3306

由于Class.forName("com.mysql.jdbc.Driver");没有抛出异常,我相信驱动程序jar就位(classPath)。只需更正用于获取连接的URL,它就可以正常工作。