【问题标题】:Issues inserting DATE value into Derby database将 DATE 值插入 Derby 数据库的问题
【发布时间】:2021-04-05 16:06:56
【问题描述】:

我正在尝试设置一个 Derby 数据库并将一些示例信息插入其中以进行测试。

获取我想要的表格的代码是...

CREATE TABLE users(
    userid varchar(128) primary key, 
    passwd_digest varchar(128)
    );
CREATE TABLE customers(
    cust_id int not null primary key(START WITH 1, INCREMENT BY 1), 
    cust_name varchar(128)
    );
CREATE TABLE orders(
    order_id int not null primary key, 
    cust_id int not null(START WITH 1, INCREMENT BY 1),
    foreign key(cust_id) references customers(cust_id), 
    order_date date, 
    order_desc varchar(128)
    );

现在,当我尝试使用以下代码将示例数据插入其中时:

insert into customers(cust_id, cust_name) values (3, 'Ringo');
insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, 12.12.1957, 'A drumset');

我从 IJ 收到以下错误:

ERROR 42X01: Syntax error: Encountered ".1957" at line 1, column 82.
Issue the 'help' command for general information on IJ command syntax.
Any unrecognized commands are treated as potential SQL commands and executed directly.
Consult your DBMS server reference documentation for details of the SQL syntax supported by your server.

我尝试通过以下方式放置日期值(忽略其他数据,只有日期似乎不起作用):

insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, 1957-12-12 00:00:00:000, 'A drumset');
insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, 1957-12-12, 'A drumset');
insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, "12-12-1957", 'A drumset');
insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, DATE("12-12-1957"), 'A drumset');
insert into orders(order_id, cust_id, order_date, order_desc) values (4, 3, 12-12-1957, 'A drumset');

但它们都会产生类似的错误,包括:

ERROR 42821: Columns of type 'DATE' cannot hold values of type 'INTEGER'. 

我不确定为什么会出现这些错误,因为我输入的值与 Derby 文档的格式匹配(至少在我看来是这样,因为它不起作用我确定我有哪里不对)。

【问题讨论】:

    标签: java sql derby


    【解决方案1】:

    使用 DATETIMESTAMP 函数或 JDBC 转义语法(无论您喜欢哪一种)将文字值转换为日期或时间戳数据类型。

    或者使用PreparedStatement 在Java 中编写插入逻辑,并使用setDate()setTimestamp() 函数。

    上述各种文档:

    1. DATE函数:https://db.apache.org/derby/docs/10.15/ref/rrefdatefunc.html
    2. TIMESTAMP函数:https://db.apache.org/derby/docs/10.15/ref/rreftimestampfunc.html
    3. 日期和时间的 JDBC 转义语法:https://db.apache.org/derby/docs/10.15/ref/rrefjdbc1020262.html
    4. PreparedStatement: https://stackoverflow.com/a/18615191/193453

    【讨论】:

    • 这行得通,我没有意识到转义是必要的。感谢您的帮助
    猜你喜欢
    • 2011-10-09
    • 2011-08-01
    • 2019-10-13
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    相关资源
    最近更新 更多