用Java连接到MySQL数据库

时间:2014-06-08 14:43:37

标签: java mysql

有人可以帮我解决这个错误吗?这是语法错误吗?

用户名:根 没有密码

代码:

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

    Connection conn = null;
    conn = DriverManager.getConnection("jdbc:mysql://localhost/main"
            + "user=root&password=");

输出:

Access denied for user ''@'localhost' to database 'mainuser=root&password='

3 个答案:

答案 0 :(得分:3)

您在?之前错过了user

DriverManager.getConnection("jdbc:mysql://localhost/main?" +
                               "user=root&password=");

值得一读Oracle Tutorial - Establishing a Connection


您也可以尝试使用Properties。看看DriverManager.getConnection(String,Properties)构造函数,还有更多的尝试。

Properties connectionProps = new Properties();
connectionProps.put("user", "root");
connectionProps.put("password", "");

String url ="jdbc:mysql://localhost/main";

Connection conn = DriverManager.getConnection(url, connectionProps);

答案 1 :(得分:0)

您可以使用以下方法签名

public static Connection getConnection(String url, String user, String password) throws SQLException

在你的情况下,它将是

conn = DriverManager.getConnection("jdbc:mysql://localhost/main", "root", "");

答案 2 :(得分:0)

你做错了 试试这个

  

(JDBC:MySQL的://本地主机/主,根,passwd中)