0

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

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")
danlooo
  • 10,067
  • 2
  • 8
  • 22
  • I've tried this but it is giving following error:Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘dbAppendTable’ for signature ‘"RODBC"’ – Hafiza Hira Bashir May 11 '22 at 11:54
  • Does [this](https://stackoverflow.com/questions/36202680/append-impossible-using-rodbcsqlsave-on-azure-sql-db) help? I only did this for SQLite so far – danlooo May 11 '22 at 12:08