简体   繁体   中英

Could not create JDBC connection to MySQL database server

The problem is I cannot connect to my MySQL database using Android Studio. I tried on Netbeans, and it works perfectly. It keeps on telling me that it could not create connection to database server, but the credentials are correct.

Versions I'm using:

  • Android Studio: 4.1.2

  • Android API: 16 4.1 (Jelly Bean)

  • MySQL Server: 8.0.18-google

  • Connector/J: 8.0.18

     String host = "jdbc:mysql://XX.XXX.XXX.X:3306/xxx_database"; String user = "root"; String password = "XXXXXXXXXXXXXXXX";

Those above are correct, tested with Netbeans and c#.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt = findViewById(R.id.text2);
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(host, user, password); <= error here
        txt.setText("Connected to database.");
    } catch (SQLException | ClassNotFoundException throwables) {
        txt.setText(throwables.getMessage());
    }

}

You must remember to put your JDBC connection code in an AsyncTask, Otherwise, it didn't work. Also, Do NOT mistake "INTERNET" permission for the "uses INTERNET" permission. You need the latter to perform JDBC

try{  
    Class.forName("com.mysql.jdbc.Driver");  
    Connection con=DriverManager.getConnection(  
    "jdbc:mysql://localhost:3306/sonoo","root","root");  
    //here sonoo is database name, root is username and password  
    Statement stmt=con.createStatement();  
    ResultSet rs=stmt.executeQuery("select * from emp");  
    while(rs.next())  
    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
    con.close();  
    }catch(Exception e){ System.out.println(e);}  
    }  

JDBC is infrequently used on Android, and I certainly would not recommend it.

IMHO, JDBC is designed for high-bandwidth, low-latency, highly-reliable network connections (eg, desktop to the database server, Web application server to database server). Mobile devices offer little of these, and none of them consistently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM