I am trying to learn how to get Microsoft SQL query results using python and pyodbc module and have run into an issue in returning the same results using the same query that I use in Microsoft SQL Management Studio.
I've looked at the pyodbc documentation and set up my connection correctly... at least I'm not getting any connection errors at execution. The only issue seems to be returning the table data
import pyodbc
import sys
import csv
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=<server>;DATABASE=<db>;UID=<uid>;PWD=<PWD>')
cursor = cnxn.cursor()
cursor.execute("""
SELECT request_id
From audit_request request
where request.reception_datetime between '2019-08-18' and '2019-08-19' """)
rows = cursor.fetchall()
for row in cursor:
print(row.request_id)
When I run the above code i get this in the python terminal window:
Process returned 0 (0x0) execution time : 0.331 s
Press any key to continue . . .
I tried this same query in SQL Management Studio and it returns the results I am looking for. There must be something I'm missing as far as displaying the results using python.
You're not actually setting your cursor up to be used. You should have something like this before executing:
cursor = cnxn.cursor()
Learn more here: https://github.com/mkleehammer/pyodbc/wiki/Connection#cursor
Related
Is there a way to list all attached databases for a sqlite3 Connection? For instance:
con = sqlite3.connect(":memory:")
con.execute("attach database 'a.db' as 'a'")
con.execute("attach database 'b.db' as 'b'")
con.list_databases() # <- doesn't exist
The command with the sqlite3 command shell is .databases. Tried poking at sqlite_master but of course that's a table, and it exists on each attached DB. I see nothing in the docs either. Is this possible?
Finally found it by digging into the sqlite3 source code:
c.execute("PRAGMA database_list").fetchall()
Forgot about PRAGMAs 🙃
(https://github.com/sqlite/sqlite/blob/master/src/shell.c.in#L8417)
I am using python 3.9 with a pyodbc connection to call a SQL Server stored procedure with two parameters.
This is the code I am using:
connectionString = buildConnection() # build connection
cursor = connectionString.cursor() # Create cursor
command = """exec [D7Ignite].[Service].[spInsertImgSearchHitResults] #RequestId = ?, #ImageInfo = ?"""
values = (requestid, data)
cursor.execute(command, (values))
cursor.commit()
cursor.close()
requestid is simply an integer number, but data is defined as follows (list of json):
[{"ImageSignatureId":"27833", "SimilarityPercentage":"1.0"}]
The stored procedure I am trying to run is supposed to insert data into a table, and it works perfectly fine when executed from Management Studio. When running the code above I notice there are no errors but data is not inserted into the table.
To help me debug, I printed the query preview:
exec [D7Ignite].[Service].[spInsertImgSearchHitResults] #RequestId = 1693, #ImageInfo = [{"ImageSignatureId":"27833", "SimilarityPercentage":"1.0"}]
Pasting this exact line into SQL Server runs the stored procedure with no problem, and data is properly inserted.
I have enabled autocommit = True when setting up the connection and other CRUD commands work perfectly fine with pyodbc.
Is there anything I'm overlooking? Or is pyodbc simply not processing my query properly? If so, are there any other ways to run Stored Procedures from Python?
Hi I'm trying to connect my Snowflake ODBC to python to create queries. I got results but I see that console display a lot of messages that hide me the results. There any way to just display the results of my query? or another way to connect with Python?
import pyodbc
con = pyodbc.connect('DSN=MYODBCNAME;UID=MYUSER')
con.setencoding(encoding='utf-8')
con.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
cursor=con.cursor()
cursor.execute("use warehouse WAREHOUSENAME;")
cursor.execute("select * from SCHEMA.DATABASE.TABLE limit 5")
while True:
row=cursor.fetchone()
if not row:
break
print(row)
Here some of those messages, but if I scroll up for some time found the results
Regards
I would recommend that you use the Snowflake Python connector to connect Snowflake to Python:
https://docs.snowflake.com/en/user-guide/python-connector.html
Hopefully someone can help me with this !! I am using cx_Oracle for oracle DB connection, I want to store a few SQL queries in excel. by running script in python, the sql can be imported from excel can be executed.
The sql1 has successfully import the sql1 but the value cannot pass to c.execute. How can I make it right? Adding """ will not help.
excel_data_df = pandas.read_excel('C:\\Python\Excel\sql.xlsx', sheet_name='SQL1')
caseno = excel_data_df['Case no']
sql1 = excel_data_df['SQL']
c = conn.cursor()
c.execute(sql1)*
Many Thanks for your help
I am using an old version of sqlalchemy (0.8) and I need to execute "REINDEX DATABASE <dbname>" on PostgreSQLql 9.4 by using sqlalchemy api.
Initially I tried with:
conn = pg_db.connect()
conn.execute('REINDEX DATABASE sg2')
conn.close()
but I got error "REINDEX DATABASE cannot run inside a transaction block".
I read in internet and tried other changes:
engine.execute(text("REINDEX DATABASE sg2").execution_options(autocommit=True))
(I tried also with autocommit=False).
and
conn = engine.raw_connection()
cursor = conn.cursor()
cursor.execute('REINDEX DATABASE sg2')
cursor.close()
I always have the same error.
I tried also following:
conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)
but I got error
Invalid value 'AUTOCOMMIT' for isolation_level. Valid isolation levels for postgresql are REPEATABLE READ, READ COMMITTED, READ UNCOMMITTED, SERIALIZABLE
What am I missing here ? Thanks for any help.