简体   繁体   English

如何在没有 ORM 的情况下用 python 编写 SQL?

[英]How to write SQL with python without an ORM?

I am connecting to a PostgreSQL database with python using os.Popen(cmd).我正在使用 os.Popen(cmd) 连接到带有 python 的 PostgreSQL 数据库。 How can I an write the SQL statement without using an ORM?如何在不使用 ORM 的情况下编写 SQL 语句?

Use psql to issue your statements to the database via the pipe.使用psql通过 pipe 向数据库发出语句。

sql = "SELECT firstname,lastname from users"
cmd = "psql -c '" + sql + ";' -d dbname -U user"  

result = os.popen(cmd, 'r', 1)
print(result)

You need to know the database schema (tables, columns, etc) ahead of time to do this.您需要提前了解数据库架构(表、列等)才能执行此操作。 You also need to be careful about SQL injection.您还需要小心 SQL 注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM