2

I am using the python-sql query builder to build queries. Below is the link: https://pypi.org/project/python-sql/

How do I execute queries from this query builder? Below is an example:

user = Table('user')

select = user.select()

tuple(select)

('SELECT * FROM "user" AS "a"', ())

How to execute this in python?

4

1 回答 1

1

It seems that python-sql only returns a tuple with the SQL string and a list of parameters. It does not execute anything. You can execute the generated code using pyodbc or other library, for example, for SQL Server:

import pyodbc
from sql import *

conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=YourServer;"
                      "Database=Your database;"
                      "Trusted_Connection=yes;")

cursor = conn.cursor()

user = Table('user')

select = user.select()

cursor.execute(select[0], select[1])

for row in cursor:
    print('row = %r' % (row,))

For other database system just change the driver name, etc...

于 2019-09-12T14:39:55.307 回答