[R] Insert a recorde into a table using SQL

Gabor Grothendieck ggrothendieck at gmail.com
Mon May 12 13:02:44 CEST 2008


Create an encoding function which replaces single quotes with
two single quotes:

# first string is a single character consisting of single quote
# second string is two characters consisting of two single quotes
enc <- function(x) gsub("'", "''", x)
dbGetQuery(con,sprintf("insert into dd (txt) values ('%s')", enc(dd[2,1])))


On Mon, May 12, 2008 at 1:54 AM, ronggui <ronggui.huang at gmail.com> wrote:
> Dear list,
>
> I want to insert a recorde into a SQLite table by dbGetQuery(), but
> there is a problem when the value contains quotation mark.
>
> > dd<-data.frame(txt=c("having both ' and \" in character.","OK"))
> > library(RSQLite)
> Loading required package: DBI
> > con<-dbConnect(dbDriver("SQLite"),":memory:")
> > dbWriteTable(con,"dd",dd,over=T)
> [1] TRUE
> > dbGetQuery(con,sprintf("insert into dd (txt) values (\"%s\")",dd[2,1]))
> NULL
> > dbGetQuery(con,sprintf("insert into dd (txt) values (\"%s\")",dd[1,1]))
> Error in sqliteExecStatement(con, statement, bind.data) :
>  RS-DBI driver: (error in statement: unrecognized token: "")")
>
> How can I insert a (key, value) pair into a table by dbGetQuery?  Thanks.
>
> --
> HUANG Ronggui, Wincent
> Bachelor of Social Work, Fudan University, China
> Master of sociology, Fudan University, China
> Ph.D. Candidate, CityU of HK.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list