开发者

How to connect to a remote MySQL database using Java?

开发者 https://www.devze.com 2023-03-31 12:15 出处:网络
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?

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?

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 = "use开发者_如何学运维rname";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}


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

give ip instead your.database.domain

0

精彩评论

暂无评论...
验证码 换一张
取 消