我是 PostgreSQL 新手,我正在尝试使用 R 将表写入 PostgreSQL。请参阅下面的 R 代码;首先制作一些可重现的数据框:
> Time<-c('201512', '201511', '201510')
> Department<-c('ABC', 'BCA', 'NBA')
> Pro_Type<-c('standard', 'maintain', 'sustaining')
> Man_month<-c('111.4', '124.1', '232.1')
> ID<-c('1','2', '3')
> melt_short<-data.frame(Time, Department, Pro_Type, Man_month, ID)
> melt_short
Time Department Pro_Type Man_month ID
1 201512 ABC standard 111.4 1
2 201511 BCA maintain 124.1 2
3 201510 NBA sustaining 232.1 3
然后创建连接:
require("RPostgreSQL")
# loads the PostgreSQL driver
drv <- dbDriver("PostgreSQL")
# creates a connection to the postgres database
con <- dbConnect(drv, dbname = "XXX",
host = "XXX.XX.XX.XXX", port = 5432,
user = "postgres", password = XXXXXX)
然后我在 PostgreSQL DB 中创建一个表:
CREATE TABLE dms_melt
(
"Time" numeric,
"Department" character(1),
"Pro_type" character(1),
"Man_month" numeric,
"ID" numeric NOT NULL,
CONSTRAINT dms_melt_pkey PRIMARY KEY ("ID")
)
WITH (
OIDS=FALSE
);
ALTER TABLE dms_melt
OWNER TO postgres;
最后执行写表代码,报错:
dbWriteTable(con, "dms_melt", value = melt_short, append = T,row.names=F)
Error in postgresqlgetResult(new.con) :
RS-DBI driver: (could not Retrieve the result : ERROR: value too long for
type character(1) CONTEXT: COPY dms_melt, line 1, column Department: "ABC"
这应该不是那么难,但我一直在寻找解决方案但徒劳无功。实际上我已经使用“mtcars”数据集来写表并且没有问题。
data(mtcars)
df <- data.frame(carname = rownames(mtcars),
mtcars,
row.names = NULL)
df$carname <- as.character(df$carname)
dbWriteTable(con, "cartable",
value = df, append = TRUE, row.names = FALSE)
[1] TRUE
插入了我创建的 PostgreSQL:
CREATE TABLE cartable
(
carname character varying,
mpg numeric(3,1),
cyl numeric(1,0),
disp numeric(4,1),
hp numeric(3,0),
drat numeric(3,2),
wt numeric(4,3),
qsec numeric(4,2),
vs numeric(1,0),
am numeric(1,0),
gear numeric(1,0),
carb numeric(1,0)
)
WITH (
OIDS=FALSE
);
ALTER TABLE cartable
OWNER TO postgres;
提前感谢您的任何建议和想法。