r - unable to update PostgreSQL table value with R's sys.time as a character using dbconnect
问题描述
i am using the below code for connecting to PostgreSQL from R.
library(DBI)
con <- dbConnect(RPostgres::Postgres(),dbname = 'postgres',
host = host_name,
port = 5432,
user = user_name,
password = password)
by using the above connection i tried to update the PostgreSQL table with sys.time() in R as character.
For that i am sending the below query to database.
dbSendQuery(con,paste0("update job_status set start_dttm=",as.character(sys.time()) ," where job_name='job';"))
but it throws the following error for me
Failed to prepare query: ERROR: syntax error at or near "04"
LINE 1: update job_status set start_dttm = 2019-03-04 04:50:12 where...
Can anyone help me to tackle this issue.
Thanks in advance.
解决方案
Valid SQL requires quotes around the date:
update job_status set start_dttm='2019-03-04 04:50:12';
Therefore, you would need
paste0("update job_status set start_dttm='", as.character(sys.time(), "';")
The above query is safe from SQL injection since sys.time()
should be safe.
However, in general (and especially when arguments are derived from user input), it is best
to use parametrized SQL to avoid SQL injection.
推荐阅读
- azure-active-directory - 如何通过 Keycloak 社交登录从 Azure AD 获取附加属性
- c# - 发布项目时,获取项目而不是尝试将 ID 推回结果是否是正确的形式?
- html - 找不到在我的网页上嵌入/播放 youtube 视频的方法
- php - PHP:通过对象属性值实例化类
- python - 在 Python 的 SQL 语句中绑定非固定变量
- azure - Azure ASP.NET Core Web App 性能较慢与 LocalHost
- c++ - C++ istream、getline、二进制文件、正则表达式和字符串的意外行为
- angular - 另一个页面上的不同导航栏和页脚Angular
- pytorch - 使用 CNN 和 pytorch 计算每个类的准确率
- flutter - 如何修复它数据未显示在颤振列表中