如何使用Java连接到远程MySQL数据库?

时间:2021-05-19 03:01:55

Can anyone provide me the Java SE coding to connect to the MySQL database in a Server (not in the localhost)? what should I put instead of "localhost" and port number?

任何人都可以提供Java SE编码连接到服务器(而不是localhost)中的MySQL数据库吗?我应该把什么代替“localhost”和端口号?

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql :// " + serverName + "/" + mydatabase; 

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}

1 个解决方案

#1


2  

simply use

String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

make sure that tou have access right to remote machine in mysql

确保tou可以访问mysql中的远程机器

give ip instead your.database.domain

给ip代替your.database.domain

#1


2  

simply use

String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

make sure that tou have access right to remote machine in mysql

确保tou可以访问mysql中的远程机器

give ip instead your.database.domain

给ip代替your.database.domain