【问题标题】:How can I use IP address (via InetAddress) to establish a connection with MySQL via JDBC?如何使用 IP 地址(通过 InetAddress)通过 JDBC 与 MySQL 建立连接?
【发布时间】:2015-10-24 08:32:29
【问题描述】:
/*
 * 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;
 }
}

我如何使用从 InerAddress 中找到的 ip 地址通过 JDBC 与 MySQL 连接?

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

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-21
        • 2020-05-08
        • 2013-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        相关资源
        最近更新 更多