python - PostgreSQL SELECT column names programmatically in python
问题描述
I would like to pass programmatically few columns from python(psycopg2) in a table.
cursor.execute("SELECT col1,col2,col3...coln FROM %s ORDER BY datetime ASC" %mytable)
column name col1,col2,col3...coln can be of length 100's and change every time cursor.execute() is called.
解决方案
You're already using string interpolation, so you could do the same for the column names. Put your column names in an array and join them when formatting the query:
columns = ['col1', 'col2', 'col3']
cursor.execute("SELECT %s FROM %s ORDER BY datetime ASC" % (','.join(columns), mytable))
It is important that the columns are strictly controlled by you and not generated from user input, as that would enable SQL injection attacks.
推荐阅读
- html - CSS 无法将文本与 ::before 和 ::after 对齐
- c - 结构中的数组分配
- maven - 如何使用 Selenium java 通过 GMail 自动发送附件
- python - 将数据附加到 json 文件中的列表
- javascript - 如何在条件语句中将字符串输入字段值与单词数组进行比较
- sql - SQL Server 中的 Oracle 安全等效项
- python - 删除数据框中每一行的列中字符串中的重复单词
- python - Anaconda 不使用激活环境中的包
- javascript - Node-Express (module.exports) 变量未定义
- php - 获取属于某个模型的所有值