使用 Java 应用程序远程连接到 H2 数据库

2023-11-27

我遇到以下问题: 当我尝试使用外部 IP 地址(PC 的 IP 而不是我的本地 IP = 我们在 cmd.exe 中运行 ipconfig 后看到的输出)创建 TcpServer 时,会发生以下错误:

服务器错误:打开端口“9092”时出现异常(端口可能正在使用中),原因:“java.net.BindException:无法分配请求的地址:JVM_Bind”[90061-169]

但是,该端口未在使用中。我已经使用 netstat -a -n 检查过。 我已启用外部 IP,并禁用了路由器的防火墙。现在可以 ping 通我的外部 IP。

请帮我。

更新:这是我启动 tcp 服务器的代码。

package businessApp;

import org.h2.tools.Server; //imports the server utility

public class startTcpServerForH2 {

    Server server; //the server's instance variable

    private static final String SERVER_IP = "192.168.1.101"; //fixed IP of the server
    private static final String SERVER_PORT = "9092"; //fixed port the server is listening to

    public void tcpServer() { //method responsible to create the tcp server

        optionPane optPane = new optionPane(); //option pane for debugging purposes, shows the server's status

        try { //catches any server related errors, if the connection is broken etc.

            //server uses the IP and port defined earlier, allows other computers in the LAN to connect and implements the secure socket layer (SSL) feature
            server = Server.createTcpServer( //create tcp server
                new String[] { "-tcpPort" , SERVER_PORT , "-tcpAllowOthers" , "-tcpSSL" }).start();

            System.out.println(server.getStatus()); //prints out the server's status
            optPane.checkServerStatus(server.getStatus()); //prints out the server's status on the option pane as well

        } catch(Exception ex){
            System.out.println("Error with Server: " + ex.getMessage());
        }
    }

    public static void main(String[] args){

        startTcpServerForH2 tcpServ = new startTcpServerForH2(); //create a new server object
        tcpServ.tcpServer(); //starts the tcp server
    }
}

第二次更新:这是 h2Connection 代码。

打包businessApp;

导入 java.sql.*; //导入sql特性

//负责与H2数据库引擎连接的类 公共类 h2Connection {

Connection conn;        //connection variable
DatabaseMetaData dbmd;  /** Metadata variable which include methods such as the following:
                         * 1) Database Product Name
                         * 2) Database Product Version
                         * 3) URL where the database files are located (in TCP mode)
                        */
Statement stm;          //statements variable
ResultSet rst;          //result sets variable

private static final String SERVER_IP = "..."; //here I enter my WAN_IP
private static final String SERVER_PORT = "9092";

public Connection connectionToH2(Connection connt) {

    optionPane optPane = new optionPane(); //create new option pane object
    String outputConn = null; //declare & initialize string which will hold important messages

    try {

        Class.forName("org.h2.Driver"); //Driver's name
        /** The String URL is pertained of the following:
         *  1) jdbc which java implements so that it can take advantage of the SQL features
         *  2) Which Database Engine will be used
         *  3) URL where the files will be stored (as this is a TCP connection)
         *  4) Schema: businessApp
         *  5) Auto server is true means that other computers can connect with the same databse at any time
         *  6) Port number of the server is also defined
         */

        String url = "jdbc:h2:tcp://" + SERVER_IP + ":" + SERVER_PORT + "/C:/Databases/businessApp;IFEXISTS=TRUE";
        System.out.println(url); //prints out the url the database files are located as well as the h2 features used (SSL)
        connt = DriverManager.getConnection(url, "sa", ""); //Driver Manager defines the username & password of the database
        System.out.println(connt.getCatalog()); //prints out the database schema
        optPane.checkServerStatus(connt.getCatalog()); //prints out the database schema on the option pane as well
        connt.setAutoCommit(false); //set AutoCommit to false to control commit actions manually

        //outputs H2 version and the URL of the database files which H2 is reading from, for confirmation
        dbmd = connt.getMetaData(); //get MetaData to confirm connection

        outputConn = "Connection to "+dbmd.getDatabaseProductName()+" "+
                   dbmd.getDatabaseProductVersion()+ " with the URL " + dbmd.getURL()+" was successful.\n";
        System.out.println(outputConn);  //outputs the message on the system (NetBeans compiler)
        optPane.checkH2Connection(outputConn); //outputs the message on top of the frame


    } catch (ClassNotFoundException ex){ //In case there is an error for creating the class for the Driver to be used
        System.out.println("Error creating class: " + ex.getMessage());
    } catch(SQLException ex){ //Any error associated with the Database Engine
        System.out.println("SQL error: " + ex.getMessage());
        optPane.checkServerStatus("SQL error: " + ex.getMessage());
    }
    return connt; //As the method is not void, a connection variable must be returned
}

}

当我想连接到 h2 数据库时,我创建一个新的 h2Connection 对象并使用它进行连接。我是按照H2手册逐字逐句进行操作的。您还需要什么?


正如下面所示的命令行帮助中所建议的,防止远程访问建议如下:

默认情况下,启动 H2 Console、TCP 服务器或 PG 服务器时,该数据库不允许来自其他计算机的连接。可以使用命令行选项启用远程访问-webAllowOthers, -tcpAllowOthers, -pgAllowOthers.

重要内容请参阅文档caveats关于这些选项。

附录:对我有用,只要我重新启动Server after打开防火墙;你不需要setProperty()根本就行;这LAN IP您的WAN_IP转发端口9092应该是你的主机IP地址;然后你可以通过你的打开一个shellWAN_IP:

java -cp h2.jar org.h2.tools.Shell -url 
    jdbc:h2:tcp://WAN_IP/~/path/to/test;ifexists=true"

命令行帮助:



$ java -cp .:/opt/h2/bin/h2.jar org.h2.tools.Shell -?
Interactive command line tool to access a database using JDBC.
Usage: java org.h2.tools.Shell 
Options are case sensitive. Supported options are:
[-help] or [-?]        Print the list of options
[-url ""]         The database URL (jdbc:h2:...)
[-user ]         The user name
[-password ]      The password
[-driver ]      The JDBC driver class to use (not required in most cases)
[-sql ""]  Execute the SQL statements and exit
[-properties ""]  Load the server properties from this directory
If special characters don't work as expected, you may need to use
 -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
See also http://h2database.com/javadoc/org/h2/tools/Shell.html

$ java -cp /opt/h2/bin/h2.jar org.h2.tools.Server -?
Starts the H2 Console (web-) server, TCP, and PG server.
Usage: java org.h2.tools.Server 
When running without options, -tcp, -web, -browser and -pg are started.
Options are case sensitive. Supported options are:
[-help] or [-?]         Print the list of options
[-web]                  Start the web server with the H2 Console
[-webAllowOthers]       Allow other computers to connect - see below
[-webDaemon]            Use a daemon thread
[-webPort ]       The port (default: 8082)
[-webSSL]               Use encrypted (HTTPS) connections
[-browser]              Start a browser connecting to the web server
[-tcp]                  Start the TCP server
[-tcpAllowOthers]       Allow other computers to connect - see below
[-tcpDaemon]            Use a daemon thread
[-tcpPort ]       The port (default: 9092)
[-tcpSSL]               Use encrypted (SSL) connections
[-tcpPassword ]    The password for shutting down a TCP server
[-tcpShutdown ""]  Stop the TCP server; example: tcp://localhost
[-tcpShutdownForce]     Do not wait until all connections are closed
[-pg]                   Start the PG server
[-pgAllowOthers]        Allow other computers to connect - see below
[-pgDaemon]             Use a daemon thread
[-pgPort ]        The port (default: 5435)
[-properties ""]   Server properties (default: ~, disable: null)
[-baseDir ]        The base directory for H2 databases (all servers)
[-ifExists]             Only existing databases may be opened (all servers)
[-trace]                Print additional trace information (all servers)
The options -xAllowOthers are potentially risky.
For details, see Advanced Topics / Protection against Remote Access.
See also http://h2database.com/javadoc/org/h2/tools/Server.html
  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 应用程序远程连接到 H2 数据库 的相关文章

  • Java new Date() 打印

    刚刚学习 Java 我知道这可能听起来很愚蠢 但我不得不问 System out print new Date 我知道参数中的任何内容都会转换为字符串 最终值是 new Date 返回对 Date 对象的引用 那么它是如何打印这个的呢 Mo
  • Spring Batch 多线程 - 如何使每个线程读取唯一的记录?

    这个问题在很多论坛上都被问过很多次了 但我没有看到适合我的答案 我正在尝试在我的 Spring Batch 实现中实现多线程步骤 有一个包含 100k 条记录的临时表 想要在 10 个线程中处理它 每个线程的提交间隔为 300 因此在任何时
  • Java JDBC:更改表

    我希望对此表进行以下修改 添加 状态列 varchar 20 日期列 时间戳 我不确定该怎么做 String createTable Create table aircraft aircraftNumber int airLineCompa
  • INSERT..RETURNING 在 JOOQ 中不起作用

    我有一个 MariaDB 数据库 我正在尝试在表中插入一行users 它有一个生成的id我想在插入后得到它 我见过this http www jooq org doc 3 8 manual sql building sql statemen
  • 多个 Maven 配置文件激活多个 Spring 配置文件

    我想在 Maven 中构建一个环境 在其中我想根据哪些 Maven 配置文件处于活动状态来累积激活多个 spring 配置文件 目前我的 pom xml 的相关部分如下所示
  • 控制Android的前置LED灯

    我试图在用户按下某个按钮时在前面的 LED 上实现 1 秒红色闪烁 但我很难找到有关如何访问和使用前置 LED 的文档 教程甚至代码示例 我的意思是位于 自拍 相机和触摸屏附近的 LED 我已经看到了使用手电筒和相机类 已弃用 的示例 但我
  • 列出jshell中所有活动的方法

    是否有任何命令可以打印当前 jshell 会话中所有新创建的方法 类似的东西 list但仅适用于方法 您正在寻找命令 methods all 它会打印所有方法 包括启动 JShell 时添加的方法 以及失败 被覆盖或删除的方法 对于您声明的
  • Liferay ClassNotFoundException:DLFileEntryImpl

    在我的 6 1 0 Portal 实例上 带有使用 ServiceBuilder 和 DL Api 的 6 1 0 SDK Portlet 这一行 DynamicQuery query DynamicQueryFactoryUtil for
  • Spring Data JPA 应用排序、分页以及 where 子句

    我目前正在使用 Spring JPA 并利用此处所述的排序和分页 如何通过Spring data JPA通过排序和可分页查询数据 https stackoverflow com questions 10527124 how to query
  • 我可以使用 HSQLDB 进行 junit 测试克隆 mySQL 数据库吗

    我正在开发一个 spring webflow 项目 我想我可以使用 HSQLDB 而不是 mysql 进行 junit 测试吗 如何将我的 mysql 数据库克隆到 HSQLDB 如果您使用 spring 3 1 或更高版本 您可以使用 s
  • Mockito when().thenReturn 不必要地调用该方法

    我正在研究继承的代码 我编写了一个应该捕获 NullPointerException 的测试 因为它试图从 null 对象调用方法 Test expected NullPointerException class public void c
  • Spring @RequestMapping 带有可选参数

    我的控制器在请求映射中存在可选参数的问题 请查看下面的控制器 GetMapping produces MediaType APPLICATION JSON VALUE public ResponseEntity
  • 总是使用 Final?

    我读过 将某些东西做成最终的 然后在循环中使用它会带来更好的性能 但这对一切都有好处吗 我有很多地方没有循环 但我将 Final 添加到局部变量中 它会使速度变慢还是仍然很好 还有一些地方我有一个全局变量final 例如android Pa
  • Java Integer CompareTo() - 为什么使用比较与减法?

    我发现java lang Integer实施compareTo方法如下 public int compareTo Integer anotherInteger int thisVal this value int anotherVal an
  • Google App Engine 如何预编译 Java?

    App Engine 对应用程序的 Java 字节码使用 预编译 过程 以增强应用程序在 Java 运行时环境中的性能 预编译代码的功能与原始字节码相同 有没有详细的信息这是做什么的 我在一个中找到了这个谷歌群组消息 http groups
  • Android 中麦克风的后台访问

    是否可以通过 Android 手机上的后台应用程序 服务 持续监控麦克风 我想做的一些想法 不断聆听背景中的声音信号 收到 有趣的 音频信号后 执行一些网络操作 如果前台应用程序需要的话 后台应用程序必须能够智能地放弃对麦克风的访问 除非可
  • 如何从泛型类调用静态方法?

    我有一个包含静态创建方法的类 public class TestClass public static
  • 如何在桌面浏览器上使用 webdriver 移动网络

    我正在使用 selenium webdriver 进行 AUT 被测应用程序 的功能测试自动化 AUT 是响应式网络 我几乎完成了桌面浏览器的不同测试用例 现在 相同的测试用例也适用于移动浏览器 因为可以从移动浏览器访问 AUT 由于它是响
  • 捕获的图像分辨率太大

    我在做什么 我允许用户捕获图像 将其存储到 SD 卡中并上传到服务器 但捕获图像的分辨率为宽度 4608 像素和高度 2592 像素 现在我想要什么 如何在不影响质量的情况下获得小分辨率图像 例如我可以获取或设置捕获的图像分辨率为原始图像分
  • 将 List 转换为 JSON

    Hi guys 有人可以帮助我 如何将我的 HQL 查询结果转换为带有对象列表的 JSON 并通过休息服务获取它 这是我的服务方法 它返回查询结果列表 Override public List

随机推荐

  • 在 C++ 中实现模拟非确定性有限自动机的代码

    我正在做自动机理论的作业 我必须确定确定性有限自动机的转换函数是否接受一个单词 我有这个输入文件 6 8 0 2 2 5 0 0 a 0 1 a 1 1 b 1 2 c 1 3 c 3 4 d 4 4 d 4 5 d 3 aaabcccc
  • SQL注入无法正常工作

    我正在尝试在我的本地主机上为安全测试项目创建的虚拟网站上执行 SQL 注入 我尝试输入字符串 OR 进入用户名和密码字段 这样它应该绕过它并显示登录正确 但相反它显示登录失败 任何有助于理解为什么 SQL 注入不起作用的帮助
  • 如何通过react js中的map方法仅访问一项

    我的问题可能不清楚 但这是我的问题 这是我使用 map 方法从数组中获取的卡片 并在每张卡片上显示每个项目 我已经触发了 编辑 按钮 以便它显示隐藏的文本 只想在一张卡片中看到它 但是 当我仅单击一张卡片时 所有卡片都会显示该隐藏消息 你能
  • CakePHP 2.x:Model::afterFind() 上的 $primary 标志实际上有用吗?

    CakePHP 的Model afterFind 回调看起来像 afterFind array results boolean primary false 根据文档 The primary参数指示当前模型是否是查询发起的模型 或者该模型是否
  • javascript数组映射方法中的Break语句[重复]

    这个问题在这里已经有答案了 可能的重复 如何像调用break一样短路Array forEach 有没有办法让我在满足条件后可以突破数组映射方法 我尝试了以下抛出 Illegal Break Statement Error 这是我随机想到的一
  • getSubscription 返回空订阅

    我是 Service Worker 和 GAE 的新手 我能够注册 Service Worker 但无法订阅 PushManager 出现订阅 null 错误 找到下面的代码以供参考 serviceWorkerRegistration pu
  • PHP 在 html 页面中显示 html 电子邮件

    我正在构建一个 PHP 电子邮件邮箱脚本 我如何使 html 电子邮件像 gmail hotmail 中那样清晰地显示 如果我只是回显它 它会影响整个页面布局 我可以使用 iframe 但这肯定不是最好的解决方案 如果您正在寻找 最佳解决方
  • 字符串太长时会被截断

    我试图从我们的服务器获取 JSON 响应 当字符串长度达到大约 5525 个字符时 响应字符串似乎总是被截断 HttpClient httpClient new DefaultHttpClient HttpPost post new Htt
  • 获取PDFBox中字符的字体高度

    PDFBox的字体类PDFont中有一个方法 名为getFontHeight 听起来很简单 但是我不太理解文档以及参数代表什么 getFontHeight这将获取字符的字体宽度 参数 c 要获取宽度的字符代码 offset 数组的偏移量 长
  • 在 Python 3 中迭代单个字节

    当迭代一个bytesPython 3 中的对象 获取个体bytes as ints gt gt gt b for b in b 123 49 50 51 如何获得 1 长度bytes对象代替 以下是可能的 但对读者来说不是很明显 并且很可能
  • 位图图像内存不足

    我知道有很多关于 android 位图图像内存不足的讨论 但我想知道是否有人可以向我解释一下 目前在我的应用程序中 我有一个列出图像缩略图 低质量 的活动 当我单击图像时 它会打开一个新活动来全屏查看图像 在我的第二次活动课中 我有 Bit
  • 关于在 Android studio 中重命名 Android 项目的建议(基于 Gradle)

    在我目前的项目中 我希望在 Android studio 0 8 9 中重命名 Android 项目并希望以后使用它 我知道论坛中讨论的两种解决方案 请有人确认最好的方法并且没有麻烦 此外 在 Android studio 0 8 9 上尝
  • 引用程序集中的条件编译

    我正在编写一个程序集 其中包含一些条件编译的成员 例如 Conditional DEBUG public static void Log string message 并像这样使用它 public void DoStuff Log This
  • 更新到 MacOS Big Sur 11.3 后 Android 设备管理器无法启动

    所以我的 Mac 刚刚强制更新到 Big Sur 11 3 我一直在尝试访问 Android 设备管理器来运行模拟设备 但每次都失败了 当我尝试从命令行运行它时 我收到以下错误消息 emulator Pixel 3a API 30 emul
  • 智能合约(Hyperledger vs Eth)[关闭]

    Closed 这个问题需要多问focused 目前不接受答案 关于智能合约的几个简单问题 超级账本智能合约 链码 与以太坊相比如何 超级账本 golang 可表达性 表现 安全 以太坊 坚固性 表达能力 表现 安全 如何保障智能合约安全 保
  • 在 iphone sdk 中以编程方式创建 sqlite 数据库

    我正在尝试在运行时以编程方式创建一个 sqlite 数据库 谁能告诉我如何在 iphone sdk 中创建它 只要调用 sqlite3 open 函数 如果路径上不存在数据库 它就会创建一个数据库 generate databasePath
  • Firebase Auth 的本地(持久身份验证状态)是否安全且不受浏览器 XSS 和 CSRF 的影响?

    我正在将 Firebase Auth 用于涉及金融交易的 Web 应用程序 因此 安全性对于我的应用程序来说是最重要的 根据this doc Firebase 可以通过将其存储在某处来在多个会话中持久保留其令牌 它没有提到它对于 XSS 的
  • 在 MySQL 存储函数中声明整型变量时出错

    尝试在 MySQL 中声明新的存储函数时出现错误 服务器版本 5 5 13 基本上 我有一个大表 它根据字符串的开始方式对字符串进行分类 我的函数接受一个字符串 来自用户输入 然后通过在数据库中搜索分类来告诉您该字符串的分类 它有点像 LI
  • 使用 Uploadify 直接 POST 到 Amazon S3

    谁能告诉我如何使用上传直接上传到Amazon S3 我的代码如下 fileInput uploadify fileDataName file uploader uploadify swf script http BUCKET NAME GO
  • 使用 Java 应用程序远程连接到 H2 数据库

    我遇到以下问题 当我尝试使用外部 IP 地址 PC 的 IP 而不是我的本地 IP 我们在 cmd exe 中运行 ipconfig 后看到的输出 创建 TcpServer 时 会发生以下错误 服务器错误 打开端口 9092 时出现异常 端