H2 Schema初始化.SQL语句中的语法错误

Kir*_*ill 5 h2 spring-boot

我有一个spring启动应用程序,我尝试在应用程序启动时初始化一些数据.

这是我的应用程序属性:

#Database connection
spring.datasource.url=jdbc:h2:mem:test_db
spring.datasource.username=...
spring.datasource.password=...
spring.datasource.driverClassName=org.h2.Driver

spring.datasource.initialize=true
spring.datasource.schema=schema.sql
spring.datasource.data=schema.sql


#Hibernate configuration
#spring.jpa.hibernate.ddl-auto = none
Run Code Online (Sandbox Code Playgroud)

这是schema.sql:

CREATE TABLE IF NOT EXISTS `Person` (
  `id`         INTEGER  PRIMARY KEY AUTO_INCREMENT,
  `first_name` VARCHAR(50) NOT NULL,
  `age`        INTEGER  NOT NULL,
  PRIMARY KEY(`id`)
);
Run Code Online (Sandbox Code Playgroud)

和data.sql

INSERT INTO `Person` (
  `id`,
  `first_name`,
  `age`
) VALUES (
  1,
  'John',
  20
);
Run Code Online (Sandbox Code Playgroud)

但是在应用程序启动时我得到了"SQL语句中的语法错误":

19:08:45.642 6474 [main] INFO  o.h.tool.hbm2ddl.SchemaExport - HHH000476: Executing import script '/import.sql'
19:08:45.643 6475 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - HHH000388: Unsuccessful: CREATE TABLE Person (
19:08:45.643 6475 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - Syntax error in SQL statement "CREATE TABLE PERSON ( [*]"; expected "identifier"
Syntax error in SQL statement "CREATE TABLE PERSON ( [*]"; expected "identifier"; SQL statement:
Run Code Online (Sandbox Code Playgroud)

我无法理解,这个SQL有什么问题.

mal*_*dao 10

此错误是由声明的结构引起的CREATE TABLE

当SQL 声明末尾有一个额外的逗号时,就会出现这样的结果-- 逗号后面没有列声明。例如:

CREATE TABLE IF NOT EXISTS `Person` (
  `id`         INTEGER  PRIMARY KEY AUTO_INCREMENT,
  `first_name` VARCHAR(50) NOT NULL,
  `age`        INTEGER  NOT NULL,     --note this line has a comma in the end
);
Run Code Online (Sandbox Code Playgroud)

这是因为CREATE TABLE需要一个将与表一起创建的列的列表,并且该列的第一个参数是identifier. 正如您在此处检查的那样,列声明遵循以下结构:

identifier datatype <constraints> <autoincrement> <functions>
Run Code Online (Sandbox Code Playgroud)

因此,就您的情况而言,正如@budthapa@Vishwanath Mataphati所提到的,您可以简单地PRIMARY KEY(id)CREATE TABLE声明中删除该行。此外,您已经id在列定义的第一行声明了这是主键。

如果您没有声明作为 PRIMARY KEY 声明,请务必检查最后一列声明后面是否有多余的逗号


小智 9

I was add below in to application.properties and it work for me

spring.jpa.properties.hibernate.globally_quoted_identifiers=true spring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions = true


bud*_*apa 7

试试这个代码.删除PRIMARY KEY(id )并执行它.

CREATE TABLE IF NOT EXISTS `Person` (
    `id`         INTEGER  PRIMARY KEY AUTO_INCREMENT,
     `first_name` VARCHAR(50) NOT NULL,
     `age`        INTEGER  NOT NULL
);
Run Code Online (Sandbox Code Playgroud)