简体   繁体   中英

I want to arrange my R code output(dataframe)containing multiple rows and columns in SQL table

I have my code written in R that gives me dataframe as an output. Now I want to insert dataframe that has multiple columns and rows in SQL table using some R code. For that purpose I connected my RStudio with SQL Server through ODBC package and used the following insert function. Actually the output of my R code works if I try to insert my output (dataframe) that has only one column with multiple rows, in one column at a time. For that purpose I was using the following code:

conn <-odbcConnect("database")
link=("https://www.ncbi.nlm.nih.gov/protein/?term=antimicrobial+peptides+AND+ 
(%221%22%5BSLEN%5D%3A+%22+50%22%5BSLEN%5D)")
AMPs<-read_html(html)
AMPs
protein_link_title<-AMPs %>% html_nodes(".title a")%>% html_text()
protein_link_title
title<- sqlQuery(conn,paste0("INSERT INTO AMPs(protein_link_title) VALUES('", 
protein_link_title, "')")) 
title`

This is the code I'm using and it is inserting the protein titles in column named "protein_link_title" which I created in SQL but this time I want to insert my R output (dataframe of multiple rows and columns), in multiple columns at once. I want to insert more VALUES in multiple columns of SQL table with R. Please help me with this. Thanks in advance.

There is the function DBI::dbAppendTable to append all rows and all columns of a data frame to a table of the data base. Keep in mind that there must be already a table in the data base having the same columns with the same types.

library(DBI)
library(odbc)

# create an example data frame to put into the data base
data <- data.frame(protein_link_title = c("Chain A", "Chain B", "Chain C"))

conn <- dbConnect(odbc(),
                  Driver = "SQL Server",
                  Server = "localhost\\SQLEXPRESS",
                  Database = "datawarehouse",
                  Trusted_Connection = "True"
)

dbAppendTable(conn = conn, value = data, name = "my_table_name")

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