You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

H2内存数据库报错:Schema ‘mytest’未找到,求解决方案

解决H2内存数据库“Schema not found”错误

问题原因

你在JDBC URL里指定的mytest是数据库名称,并非H2中的schema名称。H2默认使用PUBLIC作为默认schema,你直接用mytest.test_table1尝试创建表时,因为mytest这个schema从未被创建,所以触发“Schema not found”错误。

解决方案

方案1:使用默认PUBLIC schema(最简单)

直接移除SQL中的mytest.前缀,默认在PUBLIC schema下创建和操作表:

val con = DriverManager.getConnection("jdbc:h2:mem:mytest;MODE=MYSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1")
val stm = con.createStatement()

val sql: String =
  """
    |create table test_table1(ID INT PRIMARY KEY,NAME VARCHAR(500));
    |insert into test_table1 values (1,'A');""".stripMargin

stm.execute(sql)

方案2:创建并使用指定的mytest schema

如果必须使用mytest作为schema名称,需要先创建该schema,再进行表操作:

val con = DriverManager.getConnection("jdbc:h2:mem:mytest;MODE=MYSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1")
val stm = con.createStatement()

// 先创建mytest schema,避免重复创建用IF NOT EXISTS
stm.execute("CREATE SCHEMA IF NOT EXISTS mytest;")

val sql: String =
  """
    |create table mytest.test_table1(ID INT PRIMARY KEY,NAME VARCHAR(500));
    |insert into mytest.test_table1 values (1,'A');""".stripMargin

stm.execute(sql)

或者可以将mytest设为当前连接的默认schema,后续操作无需重复指定:

val con = DriverManager.getConnection("jdbc:h2:mem:mytest;MODE=MYSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1")
val stm = con.createStatement()

// 创建schema并设置为默认
stm.execute("CREATE SCHEMA IF NOT EXISTS mytest; SET SCHEMA mytest;")

val sql: String =
  """
    |create table test_table1(ID INT PRIMARY KEY,NAME VARCHAR(500));
    |insert into test_table1 values (1,'A');""".stripMargin

stm.execute(sql)

额外注意

你的原代码中con.createStatement缺少括号,正确写法是con.createStatement(),否则会出现编译错误。

内容的提问来源于stack exchange,提问作者baron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:35:32