如何在postgresql中向表插入值

如何在postgresql中向表插入值,sql,postgresql,Sql,Postgresql,当我尝试向表中插入值时,它不起作用,出现以下错误: ERROR: invalid input syntax for integer: "regular" LINE 2: ('100', 'Astronomy Today', '1st publisher', 6, 'regular', 4/... ^ 这是我的代码: CREATE TABLE Subscribe

当我尝试向表中插入值时,它不起作用,出现以下错误:

ERROR:  invalid input syntax for integer: "regular"
LINE 2: ('100', 'Astronomy Today', '1st publisher', 6, 'regular', 4/...
                                                                   ^
这是我的代码:

CREATE TABLE Subscribes
(cid numeric(5,0),
title varchar (30),
publisher varchar(30),
period integer, 
offer varchar (10), 
sfrom date,
primary key(cid, title, publisher, offer, period),
foreign key(cid) references Customer(cid),
foreign key(title, publisher,offer, period) references Pricing(title, 
publisher,offer, period));


INSERT INTO Subscribes VALUES
('100', 'Astronomy Today', '1st publisher', 6, 'regular', 4/4/2015),
('100', 'Bridal Guide', '3rd publisher', 12, 'regular', 1/5/2015),
('100', 'Click Magazine', '3rd publisher', 6, 'regular', 20/12/2014),
('107', 'Bridal Guide', '3rd publisher', 12, 'regular', 29/4/2015);

PS:我检查了每个变量,没有发现问题

在日期前后加上单引号,如下所示

INSERT INTO Subscribes VALUES
('100', 'Astronomy Today', '1st publisher', 6, 'regular', '2015/4/4')

有人比我快:)


您在插入日期字段时遇到问题,它没有被引用。。。而且它的格式不是很好。您应该使用标准系统格式“2015-04-04”或在插入中使用从文本到日期(文本,文本)的转换功能

使用
INSERT
时,应注意编写的代码:

  • 始终明确列出列
  • 不要用单引号括起数字
  • 对日期常量使用正确的格式
因此,它应该更像这样:

INSERT INTO Subscribes(cid, title, publisher, period, offer, sfrom)
     VALUES (100, 'Astronomy Today', '1st publisher', 6, 'regular', '2015-04-04'), . . .
INSERT INTO Subscribes 
  (cid, title, publisher, period, offer, sfrom)
VALUES 
(100, 'Astronomy Today', '1st publisher', 6, 'regular', date '2015-04-04'),
(100, 'Bridal Guide', '3rd publisher', 12, 'regular', date '2015-05-01'),
(100, 'Click Magazine', '3rd publisher', 6, 'regular', date '2014-12-20'),
(107, 'Bridal Guide', '3rd publisher', 12, 'regular', date '2015-04-29');

若要插入日期,请使用该日期

以下插入内容适用于您的案例:

INSERT INTO Subscribes(cid, title, publisher, period, offer, sfrom)
VALUES (100, 'Astronomy Today', '1st publisher', 6, 'regular', TO_DATE('04/04/2015', 'DD/MM/YYYY'))

2015年4月29日
不是有效的日期文字。要么使用正确的ANSI文本:
date'2015-04-29'
,要么使用
to_date()
函数(我更喜欢ANSI文本,因为它的类型更少)

'100'
不是一个数字,而是一个字符文字。数字不需要单引号。改用
100

您还应始终限定列名,以使语句更加健壮:

INSERT INTO Subscribes  (cid, title, publisher, period, offer, sfrom)
将所有这些放在一起,结果如下:

INSERT INTO Subscribes(cid, title, publisher, period, offer, sfrom)
     VALUES (100, 'Astronomy Today', '1st publisher', 6, 'regular', '2015-04-04'), . . .
INSERT INTO Subscribes 
  (cid, title, publisher, period, offer, sfrom)
VALUES 
(100, 'Astronomy Today', '1st publisher', 6, 'regular', date '2015-04-04'),
(100, 'Bridal Guide', '3rd publisher', 12, 'regular', date '2015-05-01'),
(100, 'Click Magazine', '3rd publisher', 6, 'regular', date '2014-12-20'),
(107, 'Bridal Guide', '3rd publisher', 12, 'regular', date '2015-04-29');