JDBC: connect to remote mySQL database?

2019-08-04 13:01发布

问题:

    public void readDataBase() throws Exception {
    try {
        // This will load the MySQL driver, each DB has its own driver
        Class.forName("com.mysql.jdbc.Driver");
        // Setup the connection with the DB
        connect = DriverManager
                .getConnection("jdbc:mysql://185.28.21.11/u505743489_db?"+ "user=u505743489_db&password=password");

        // Statements allow to issue SQL queries to the database
        statement = connect.createStatement();
        // Result set get the result of the SQL query
        resultSet = statement
                .executeQuery("select * from FEEDBACK.COMMENTS");
        writeResultSet(resultSet);

        // PreparedStatements can use variables and are more efficient
        preparedStatement = connect
                .prepareStatement("insert into  FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
        // "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
        // Parameters start with 1
        preparedStatement.setString(1, "Test");
        preparedStatement.setString(2, "TestEmail");
        preparedStatement.setString(3, "TestWebpage");
        preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
        preparedStatement.setString(5, "TestSummary");
        preparedStatement.setString(6, "TestComment");
        preparedStatement.executeUpdate();

        preparedStatement = connect
                .prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
        resultSet = preparedStatement.executeQuery();
        writeResultSet(resultSet);

        // Remove again the insert comment
        preparedStatement = connect
                .prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
        preparedStatement.setString(1, "Test");
        preparedStatement.executeUpdate();

        resultSet = statement
                .executeQuery("select * from FEEDBACK.COMMENTS");
        writeMetaData(resultSet);

    } catch (Exception e) {
        throw e;
    } finally {
        close();
    }

}

I tried this code, but it gives:
Exception in thread "main" java.sql.SQLException: null, message from server: "Host 'mobile-130-126-255-40.near.illinois.edu' is not allowed to connect to this MySQL server"

I googled about this and it seems that I have to grant privileges to the database, but I don't know where my MySQL command prompt is. Is there any way to grant privileges in phpMyAdmin?
Any help would be appreciated!

回答1:

hit windows+r then type "cmd" in it and hit enter.. this will open command prompt for windows.

then go.. mysql -u user_name -p press_enter_key

then type password

i.e.

line-1 : mysql -u root -h localhost -p

line-2 : admin

where 'admin' is your password.

then..

mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';