Q: apply for each row and specific column in R to Insert data to database I am tring to understand how to use apply function in R. I know that it is very important to use, especially when we want to override a for loop, which is not optimal.
Let's take dataframe:
  df <- data.frame(
    Product_Id = c(2,4,6,8),
    Quantity = c(40,30,20,10)
  )

and parameters:
Timestamp = Sys.time()
Name <- 'John'
Surname <- 'Smith'

I would Like to this values to database so I created:
apply(UpdateData[1], 2, function(x){paste('INSERT INTO "Table"(Product_Id", "Quantity", "Name", "Surname", "Timestamp") VALUES (', UpdateData$Product_Id, ', ', UpdateData$Quantity,',\'',Name, '\',\'', Surname,'\',\'',Timestamp,'\');', sep = "")})

I Got:
     Product_Id                                                                                                                                        
[1,] "INSERT INTO \"Table\"(Product_Id\", \"Quantity\", \"Name\", \"Surname\", \"Timestamp\") VALUES (2, 10,'John','Smith','2021-07-23 13:32:34 GMT');"
[2,] "INSERT INTO \"Table\"(Product_Id\", \"Quantity\", \"Name\", \"Surname\", \"Timestamp\") VALUES (4, 20,'John','Smith','2021-07-23 13:32:34 GMT');"
[3,] "INSERT INTO \"Table\"(Product_Id\", \"Quantity\", \"Name\", \"Surname\", \"Timestamp\") VALUES (6, 30,'John','Smith','2021-07-23 13:32:34 GMT');"
[4,] "INSERT INTO \"Table\"(Product_Id\", \"Quantity\", \"Name\", \"Surname\", \"Timestamp\") VALUES (8, 40,'John','Smith','2021-07-23 13:32:34 GMT');"

To Insert data to database I decided to add connection function:
apply(UpdateData[1], 2, function(x){dbFetch(dbSendQuery(con, paste('INSERT INTO "Table"(Product_Id", "Quantity", "Name", "Surname", "Timestamp") VALUES (', UpdateData$Product_Id, ', ', UpdateData$Quantity,',\'',Name, '\',\'', Surname,'\',\'',Timestamp,'\');', sep = "")), n = -1)})

I got error:
 Error: Expecting a single string value: [type=character; extent=4]. 

When I use for loop it works fine.
Can it be done with apply or related functions?

A: I believe this is the difference between calling and passing a function through apply functions.  You can only pass a function rather than call. I believe it should work if you create the function outside and pass it through apply...probably should use sapply for a string creation.  Cannot try out on my end because I don have the packages or the connection.  Try this:
db_function<- function(x,y,n){dbFetch(dbSendQuery(con,
                       paste('INSERT INTO "Table"(Product_Id", "Quantity", "Name", "Surname", "Timestamp") VALUES (', 
                             x, ', ', y,',\'',Name, '\',\'', Surname,'\',\'',Sys.time(),'\');', 
                             sep = "")), n = n)})


sapply(1:NROW(UpdateData[1,], db_function, y = UpdateData$Quantity, n = -1)

