user3702643
user3702643

Reputation: 1505

Connecting to MySQL database in Java

Can anyone help me out with this error here? Is it a syntax error?

Username:root No password

Code:

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

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

Output:

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

Upvotes: 0

Views: 72

Answers (3)

Braj
Braj

Reputation: 46881

You missed ? before user.

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

It's worth reading Oracle Tutorial - Establishing a Connection


You can try with Properties as well. Look at DriverManager.getConnection(String,Properties) constructor and there are more try with any one.

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

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

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

Upvotes: 3

Jain
Jain

Reputation: 984

You're doing it wrong Try this

(Jdbc:mysql://localhost/main,root,passwd)

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 69035

You can use the following method signature instead

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

In your case it will be

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

Upvotes: 0

Related Questions