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()
Related
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("----")
I'm using cx_oracle to update record data in oracle from python. It just a simple update, but it takes forever to run and timeout in the end. If I run the same statement directly from Oracle, it works perfectly. Does anyone know why this happened? Thanks!
my code:
con = cx_Oracle.connect()
cur = con.cursor()
stmt = "UPDATE table SET rank = 4 WHERE id like 'SAP_1000141471' and rank = 2"
cur.execute(stmt)
con.commit()
result =cur.fetchall()
I'm currently trying to query a deltadna database. Their Direct SQL Access guide states that any PostgreSQL ODBC compliant tools should be able to connect without issue. Using the guide, I set up an ODBC data source in windows
I have tried adding Set nocount on, changed various formats for the connection string, changed the table name to be (account).(system).(tablename), all to no avail. The simple query works in Excel and I have cross referenced with how Excel formats everything as well, so it is all the more strange that I get the no query problem.
import pyodbc
conn_str = 'DSN=name'
query1 = 'select eventName from table_name limit 5'
conn = pyodbc.connect(conn_str)
conn.setdecoding(pyodbc.SQL_CHAR,encoding='utf-8')
query1_cursor = conn.cursor().execute(query1)
row = query1_cursor.fetchone()
print(row)
Result is ProgrammingError: No results. Previous SQL was not a query.
Try it like this:
import pyodbc
conn_str = 'DSN=name'
query1 = 'select eventName from table_name limit 5'
conn = pyodbc.connect(conn_str)
conn.setdecoding(pyodbc.SQL_CHAR,encoding='utf-8')
query1_cursor = conn.cursor()
query1_cursor.execute(query1)
row = query1_cursor.fetchone()
print(row)
You can't do the cursor declaration and execution in the same row. Since then your query1_cursor variable will point to a cursor object which hasn't executed any query.
I am using Python 2.7 and pyodbc to talk to a Postgresql database. The execute statement freezes and does not return when I use prepared statement. If I use straight sql then it works fine. Any ideas?
Here is what I have in code:
DBconn = pyodbc.connect("DSN=devDB;UID=dev;PWD=dev", autocommit=True)
cursor = DBconn.cursor()
sql = """ select distinct age from user where name = (?) """
params = ('john',)
cursor.execute(sql, params)
#works fine
#sql = """ select distinct age from user where name = 'john' """
#cursor.execute(sql)
row = cursor.fetchone()
print(row)
cursor.close()
DBconn.close()
PS: This query should only return one row and there is data is really small.
I'm trying to store the current time in my access database with the following script:
import pyodbc
import time
connStr = """
DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
DBQ=C:/Users/QPCS Registration/Documents/DB Tests/PYODBC.accdb;
"""
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
def TimeStamp():
RFID = str(input("Please tap your pass on the reader:\n"))
Current_Time = str(time.strftime("%H:%M"))
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number,Time_Tapped) VALUES('+RFID+','+Current_Time+');')
cnxn.commit()
def Close_DB_Cnxn():
cnxn.close()
TimeStamp()
Close_DB_Cnxn()
When I run it I get the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression '19:44'. (-3100) (SQLExecDirectW)")
The problem is definitely with 'Current_Time', because when I try to store the variable 'RFID' with the script shown below, it inserts into the database just fine.
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number) VALUES('+RFID+');')
I have tried changing the data type of the field 'Time_Tapped' in the table 'Time_Of_Entry' from Short Text, to Date/Time;Short Time but that has had no effect.
My machine is running on windows 7 home premium 64-bit. I have Microsoft office 2010; 32-bit I'm running python 3.3; 32-bit
Parameterized queries are useful for both INSERT queries and SELECT queries when Date/Time values are involved. Instead of messing with date/time formats and delimiters you just pass the Date/Time value as a parameter and let the data access layer (ODBC in this case) sort it out.
The following example works for me:
from datetime import datetime, time
import pypyodbc
rfid = "GORD123" ## for testing
now = datetime.now()
currentTime = datetime(1899, 12, 30, now.hour, now.minute)
connStr = """
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
Dbq=C:/Users/Public/Database1.accdb;
"""
cnxn = pypyodbc.connect(connStr)
cursor = cnxn.cursor()
sql = """
INSERT INTO Time_Of_Entry (RFID_Number, Time_Tapped) VALUES (?, ?)
"""
parameters = (rfid, currentTime)
cursor.execute(sql, parameters)
cursor.close()
cnxn.commit()
cnxn.close()
Notes:
I used pypyodbc instead of pyodbc because I was using Python 3.4.3 and the latest pyodbc installer for Windows choked when it couldn't find Python 3.3. To get pypyodbc all I had to do was run pip install pypyodbc.
All date/time values in Access have both a date and time component. In order for a date/time value to appear by default as time-only in Access we need to assign it the "magic" date 1899-12-30. (That's the date corresponding to CDate(0) in Access.)