简体   繁体   中英

Inserting R code output(dataframe )in multiple columns of sql table at once

For example I made an SQL table with column names "Names", "Class", "age" and I have a data-frame which I made using R code:

data_structure1<- as.data.frame("Name")
data_structure1
data_structure2<-as.data.frame("Class")
data_structure2
data_structure3<-as.data.frame("age")
data_structure3
final_df<- cbind(data_structure1,data_structure2,data_structure3)
final_df

#dataframe "Name" contains multiple entries as different names of students. #dataframe "Class" contains multiple entries as classes in which student are studying like 1,2,3,4 etc. #dataframe "age" contains multiple entries as ages of students. I want to insert final_df in my SQL table containing column names as "Names", "Class", "age". Below is the command which I am using for inserting only one column in one column of SQL table and this is working fine for me.

title<- sqlQuery(conn,paste0("INSERT INTO AMPs(Names) VALUES('",Names, "')")) 
title

But this time I want to insert a dataframe of multiple columns in multiple columns of SQL table. Please help me with this. Thanks in advance.

Using the DBI package and a package for your database (eg, RPostgres ) you can do something like this, assuming the table already exists:

AMPs <- data.frame(name = c("Foo", "Bar"),  Class = "Student", age = c(21L, 22L))


conn <-   DBI::dbConnect(...) # read doc to set parameters
## Create a parameterized INSERT statement 
db_handle <- DBI::dbSendStatement(
  conn,
  "INSERT INTO AMPs (Name, Class, age) VALUES ($1, $2, $3)"
)
## Passing the data.frame
DBI::dbBind(db_handle, params = unname(as.list(AMPs)))

DBI::dbHasCompleted(db_handle)

## Close statement handle and connection
DBI::dbClearResult(db_handle)
DBI::dbDisconnect(conn)

You may also want to look at DBI::dbAppendTable .

Edit : The example above works with PostgreSQL, and I see that the OP tagged the question with 'sql-server'. I don't have means for testing it with SQL Server, but the DBI interface aims at being general so I believe it should work. One important thing to note is the syntax, and, in particular, the syntax for the bind parameters. In PostgreSQL the parameters are defined as $1 for the first parameter, $2 for the second and so on. This might be different for other databases. I think SQL Server is using ? , and that that the binding is done based on position - ie, the first ? is bind to the first supplied parameter, the second ? to the second and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM