Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Update a mysql table with data frame

Tags:

r

dbi

rmysql

dbplyr

I have a MariaDB and I want to update a table with a local R data frame. As an example, I have a table with these column names:

id,foo,bar

id is the primary key on the data base table.

Is there a function with which I can easily update the remote data base with my local data frame? Ideally, I am looking for something like this:

update_table(con, remote_table_name, local_data_frame, primary_key="id")

I am aware that I could write the SQL statement like this into a string and then execute it with DBI::dbSendStatement(con, query):

INSERT INTO mytable (id, foo, bar)
VALUES (1, 'a1', 'b1'),
(2, 'a2', 'b2'),
(3, 'a3', 'b3'),
(4, 'a4', 'b4'),
ON DUPLICATE KEY UPDATE id=VALUES(id),
foo=VALUES(foo),
bar=VALUES(bar)

But I would be surprised if there is not an out-of-the-box solution for this seemingly simple operation. Does anybody have an idea if such a function is embedded in a package?

like image 953
MKR Avatar asked Oct 18 '25 06:10

MKR


1 Answers

The dbx package has a function which does exactly what I needed:

dbxUpdate(db, table, records, where_cols=c("id"))

It does work with MariaDB.

like image 141
MKR Avatar answered Oct 19 '25 21:10

MKR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!