I'm using this simple script, however, the for loop never executes. The script is terminated without any error - but the data is in the database. 2 weeks ago this script worked fine.
Does anyone know where the problem may be?
Thank you.
import pyodbc
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=S:\Chat_OV_UL\O2Spokojenost\DtbO2Spokojenost.accdb;', autocommit=True)
cursor = conn.cursor()
cursor.execute('select * from t_prepair')
print ("Databáze načtena")
limita = 0
for row in cursor.fetchall():
limita = limita + 1
print(row[0])
print(limita)
print("----")
Related
I am using QODBC Driver to connect to my Quickbooks Data. Until now, I was the QODBC directly in Power BI/Excel and QODBC works perfectly fine there. But today, I tried to connect to QODBC using python and it is giving me the following error
The python code I am using is this
import pyodbc
cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote;')
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")
for row in cursor.fetchall():
print (row)
cursor.close()
cn.close()
Can anyone see what's the reason for this error?
After a lot of googling, I found the answer. I don't know why but the pyodbc.connect statement requires one more parameter i.e. "autocommit=True". So, the updated code now looks like this and it is working perfectly fine.
import pyodbc
# pyodbc.pooling = False
cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote',autocommit=True)
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")
for row in cursor.fetchall():
print (row)
cursor.close()
cn.close()
I have a pretty weird problem, I am trying to extract with Python a SQL database in Azure.
Within this database, there are several tables (I explain this because you gonna see a "for" loop in the code).
I can import some tables without problem, others (the ones that take the longest, I suppose it is because size) fail.
Not only does it throw an error ( [1] 25847 killed / usr / bin / python3 ), but it directly kicks me out of the console.
Does anyone know why? Is there an easier way to calculate the size of the database without import the entire database with pd.read_sql ()?
code:
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
query = "SELECT * FROM INFORMATION_SCHEMA.TABLES"
df = pd.read_sql(query, cnxn)
df
DataConContenido = pd.DataFrame({'Nombre':[], 'TieneCon?':[],'Size':[]})
for tablas in df['TABLE_NAME']:
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
query = "SELECT * FROM " + tablas
print("vamos con "+ str(tablas))
try:
df = pd.read_sql(query, cnxn)
size=df.shape
if size[0] > 0:
DataConContenido= DataConContenido.append(dict(zip(['Nombre','TieneCon?','Size'],[tablas,True,size])),ignore_index=True)
else:
DataConContenido= DataConContenido.append(dict(zip(['Nombre','TieneCon?','Size'],[tablas,False,size])),ignore_index=True)
except:
pass
Could it be that the connection drops when it takes so long and that is why the error named above?
I think the process is getting killed in the below line :
DataConContenido= DataConContenido.append(dict(zip(['Nombre','TieneCon?','Size'],[tablas,True,size])),ignore_index=True)
You could double confirm by adding a print statement just above it.
print("Querying Completed...")
You are getting KILLED mainly because there is a probability that your process crossed some limit in the amount of system resources that you are allowed to use. This specific operation to me appears like one.
If possible you could query and append in batches rather than doing in one shot.
I'm new to Python. Only been coding a month. I am stumped. The below code works perfectly until I move it to a function. I'm not at work so I can't remember the exact error, but it was something about no temp registry access. The exact error is not important since the code is working. What I can't figure out is why I can't call this code from a function. I can import this code with 'from filename.py import *' and it works.
Can an experienced Python coder explain why the access connection will not work in a function call?
import pypyodbc
gage_list = []
gage=0
ser_num=1
owner=2
duedate=3
status=4
#create connection
DBfile = "C:/ProgramData/CyberMetrics Corporation/GAGEtrak 7.0/AppFiles/Gtw70.accdb"
conn = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBfile)
cursor = conn.cursor()
cursor.execute("SELECT Gage_ID FROM Gage_Master")
Gage_ID=cursor.fetchall()
cursor.execute("SELECT Gage_SN FROM Gage_Master")
Gage_SN=cursor.fetchall()
cursor.execute("SELECT GM_Owner FROM Gage_Master")
GM_Owner=cursor.fetchall()
cursor.execute("SELECT Next_Due_Date FROM Gage_Master")
Next_Due_Date=cursor.fetchall()
cursor.execute("SELECT Status FROM Gage_Master")
Status=cursor.fetchall()
conn.close()
counter = 0
for i in range(len(Gage_ID)): #combines gage columns into an array
tup = Gage_ID[i][0], Gage_SN[i][0], GM_Owner[i][0], Next_Due_Date[i][0], Status[i][0]
gage_list.append(tup)
print(gage_list[14][duedate]) #to choose a field, select from gage, ser_num, owner, duedate, or status variables
So, after coding with pyodbc for a couple days now, I've run into a road block it seems. My SQL update will not work, even after putting autocommit=True in the connection statement. Nothing changes in the database at all. All my code is provided below. Please help. (I am using the 2016 version of MS Access, code runs with no errors, 32 bit Python and Access.)
import pyodbc
# Connect to the Microsoft Access Database
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:\Users\User_Name\Desktop\Databse\CPLM.accdb'
)
cnxn = pyodbc.connect(conn_str, autocommit=True)
crsr = cnxn.cursor()
crsr2 = cnxn.cursor()
# SQL code used for the for statement
SQL = "SELECT NameProject, Type, Date, Amount, ID FROM InvoiceData WHERE Type=? OR Type=? OR Type IS NULL AND ID > ?"
# Defining variables
date = ""
projectNumber = 12.04
numberDate = []
# Main Code, for each row in the SQL query, update the table
for row in crsr.execute(SQL, "Invoice", "Deposit", "1"):
print (projectNumber)
if row.NameProject is not None:
crsr2.execute("UPDATE Cimt SET LastInvoice='%s' WHERE Num='%s'" % (date, projectNumber))
cnxn.commit()
# Just used to find where to input certain data.
# I also know all the code in this if statement completes due to outside testing
projectNumber = row.NameProject[:5]
numberDate.append([projectNumber, date])
else:
date = row.Date
print(numberDate)
crsr.commit()
cnxn.commit()
cnxn.close()
I am currently connecting to a Sybase 15.7 server using sybpydb. It seems to connect fine:
import sys
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib')
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/lib')
import sybpydb
conn = sybpydb.connect(user='usr', password='pass', servername='serv')
is working fine. Changing any of my connection details results in a connection error.
I then select a database:
curr = conn.cursor()
curr.execute('use db_1')
however, now when I try to run queries, it always returns None
print curr.execute('select * from table_1')
I have tried running the use and select queries in the same execute, I have tried including go commands after each, I have tried using curr.connection.commit() after each, all with no success. I have confirmed, using dbartisan and isql, that the same queries I am using return entries.
Why am I not getting results from my queries in python?
EDIT:
Just some additional info. In order to get the sybpydb import to work, I had to change two environment variables. I added the lib paths (the same ones that I added to sys.path) to $LD_LIBRARY_PATH, i.e.:
setenv LD_LIBRARY_PATH "$LD_LIBRARY_PATH":dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib:/dba/sybase/ase/15.7/OCS-15_0/lib
and I had to change the SYBASE path from 12.5 to 15.7. All this was done in csh.
If I print conn.error(), after every curr.execute(), I get:
("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)
I completely understand where you might be confused by the documentation. Its doesn't seem to be on par with other db extensions (e.g. psycopg2).
When connecting with most standard db extensions you can specify a database. Then, when you want to get the data back from a SELECT query, you either use fetch (an ok way to do it) or the iterator (the more pythonic way to do it).
import sybpydb as sybase
conn = sybase.connect(user='usr', password='pass', servername='serv')
cur = conn.cursor()
cur.execute("use db_1")
cur.execute("SELECT * FROM table_1")
print "Query Returned %d row(s)" % cur.rowcount
for row in cur:
print row
# Alternate less-pythonic way to read query results
# for row in cur.fetchall():
# print row
Give that a try and let us know if it works.
Python 3.x working solution:
import sybpydb
try:
conn = sybpydb.connect(dsn="Servername=serv;Username=usr;Password=pass")
cur = conn.cursor()
cur.execute('select * from db_1..table_1')
# table header
header = tuple(col[0] for col in cur.description)
print('\t'.join(header))
print('-' * 60)
res = cur.fetchall()
for row in res:
line = '\t'.join(str(col) for col in row)
print(line)
cur.close()
conn.close()
except sybpydb.Error:
for err in cur.connection.messages:
print(f'Error {err[0]}, Value {err[1]}')