I am new to PostgreSQL and I'm trying to use R to write table to PostgreSQL. See the R code below; make some reproducible data frame first:
> 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
then creates the connection:
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)
then I create a table in 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;
Finally execute the write table code and got the error:
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"
It should be not so hard but I've been searching for solution for a while but in vain. And actually I've used the "mtcars" data set to write table and with no problem.
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
inserted the PostgreSQL which I created as:
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;
Thanks in advance for any suggestions and ideas.