pythonpython-3.xpython-sql

How to execute query formed by python-sql query builder?


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?


Solution

  • 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...