Solution java code to connect MySql is not accessible via IP, and can only 127.0.0.1 localhost access

Write some code to test the database connection, mysql database to test the connection with a variety of IP of the machine, and with 127.0.0.1 localhost access is not a problem, the normal access to the database, but can not use IP access. After testing, to find the right way to paste.

code show as below:

package com.jr;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class testmysql {
    public static void main(String[] args){
        //String URL="jdbc:mysql://127.0.0.1:3306/hadoopdb?";

         //String URL="jdbc:mysql://localhost:3306/hadoopdb?";
        //String URL="jdbc:mysql://192.168.2.1:3306/hadoopdb?";                //VMnet1 IP
        //String URL="jdbc:mysql://192.168.1.9:3306/hadoopdb?";                //无限局域网IP
        String URL="jdbc:mysql://192.168.193.1:3306/hadoopdb?";              //VMnet8 IP
        String USER="admin";
        String PASSWORD="123456";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection(URL, USER, PASSWORD);
            Statement st=conn.createStatement();
            ResultSet rs=st.executeQuery("select * from users");
            while(rs.next()) {
                System.out.println(rs.getString("name"));
            }
            rs.close();
            st.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Native IP:

 

 

 

Most of the new installation of mysql database ip default is not open access, so that we in the application and the database server is not the same need to turn this mode,

Solution:

cmd way into the mysql command line enter the mysql bin directory, such as database user name is root, password is 123456

mysql -uroot -p123456 // landing mysql,

use mysql; // switch to database mysql

update user set host = '%' where user = 'root' and host = 'localhost'; // modified host is a wildcard can access any ip

. grant all privileges on * * to 'root' @ '%' identified by 'root'; // given root privileges 
flush privileges; // take effect, or restart the mysql service without restarting the brush into the configuration memory 

The above steps can make IP can be connected, and if it can not be connected to restart mysql service

5. Restart mysql

Into the bin directory of mysql

Turn off mysql database: net stop mysql

Then restart the mysql database: net start mysql

Completed.

And then run the code into eclipse can be successful. I was more than a variety of IP network adapter are tested successfully.

 

Guess you like

Origin blog.csdn.net/nengyu/article/details/85010560