无法将我的Java App与我的SQL数据库连接

时间:2014-12-07 14:47:08

标签: java mysql mysql-connector

我遇到了这个错误:

Exception in thread "main" java.lang.ClassNotFoundException: com.msql.jdbc.Driver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at test.main(test.java:12)

这是我的代码:

import java.sql.*;
import com.mysql.jdbc.Statement;

public class test {

    public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        String url = "jdbc:mysql://localhost:3306/test";
        Statement sql;

        ResultSet rs;
        Class.forName("com.msql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection(url, "root", "root");

        sql = (Statement) con.createStatement();
        rs = sql.executeQuery("select*from persoane");

        while (rs.next()) {
            System.out.println("id=" + rs.getInt("Id") + ", name= " + rs.getString("name") + ", age=" + rs.getInt(3));
        }
    }
}

我不明白为什么。

我创建了我的项目,我去了Project,Project Properties,Libraries,Add External Jars 并添加了mysql-connector-java-5.1.34-bin

1 个答案:

答案 0 :(得分:4)

错字:

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

应该是

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

可以简化为

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

事实上,由于MySQL使用JDBC type 4 driver

,因此可以完全省略此声明