I want to select data from my database using a python script. The connection is working fine, and the query is working when I am executing it in the SQL server management system
, but doesn't work when I use pyodbc
.
the query:
SELECT TOP 1 * FROM [cities]
ORDER BY NEWID()
the pyodbc
interpretation:
def sqlexec(conn, query:str, print_:bool = False, return_ = False):
cursor = conn.cursor()
answer = cursor.execute(query).fetchall()
if print_:
for row in cursor:
print(row)
conn.commit()
if return_:
return answer
cursor = sqlexec(conn,
'''use [law and order]
go
SELECT TOP 1 * FROM [cities]
ORDER BY NEWID()''',
return_=True)
for row in cursor:
print(row)
law and order
is the name of the database, and cities
is the name of the table I am selecting random information from