繁体   English   中英

如何使用 IP 地址(通过 InetAddress)通过 JDBC 建立与 MySQL 的连接?

[英]How can I use IP address (via InetAddress) to establish a connection with MySQL via JDBC?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package inventory;

import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author Imantha
 */
public class dbcon {

  public static Connection createmyConnection() throws Exception{

    InetAddress ip=InetAddress.getLocalHost();
    String s=ip.getHostAddress();
    Class.forName("com.mysql.jdbc.Driver");
    Connection c = DriverManager.getConnection("jdbc:mysql://localHost:3306/inventory","root","123");   
    return c;
 }
}

我如何使用通过 JDBC 与 MySQL 连接的 InerAddress 找到的 ip addre?

我想替换本地主机并添加 s(捕获 ip 地址)

你不能。 您不需要将InetAddress与 JDBC 一起使用。 您只需要构建一个正确的 JDBC URL。

自 2007 年以来,您也不需要Class.forName()行。

如果只替换它你想要的,那么

Connection c=DriverManager.getConnection("jdbc:mysql://"+s+"/inventory","root","123");

只需更改连接 URL 以获取存储在变量s IP 地址

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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