I'm trying to fetch some data from a column whose DATA_TYPE=NUMBER(1,0) with this piece of code:
import cx_Oracle
conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("SELECT DELETED FROM SERVICEORDER WHERE ORDERID='TEST'")
print(cursor.fetchone()[0])
which complains thus:
Traceback (most recent call last):
File "main.py", line 247, in <module>
check = completed()
File "main.py", line 57, in completed
deleted = cursor.fetchone()[0]
cx_Oracle.DatabaseError: OCI-22061: invalid format text [T
Replacing 'DELETED' column with one whose DATA_TYPE=VARCHAR2 does not throw such a complaint.
I am running in to this problem now using cx_Oracle 5.0.4 with Unicode support. The above accepted solution did not work for me. The DELETED column in the question is a Numeric column, which is what causes this bug.
According to the mailing list ( http://comments.gmane.org/gmane.comp.python.db.cx-oracle/2390 ) it may be a bug in Oracle that shows only in cx_Oracle with Unicode support.
from the link:
"When I build cx_Oracle without Unicode support, it all works as expected.
When I build cx_Oracle with Unicode support, attempting to use a query
that returns a numeric value (such as):
con = Connection( ... )
cur = con.cursor()
cur.execute( 'SELECT 1 FROM DUAL' )
rows = cur.fetchall()
results in this exception:
cx_Oracle.DatabaseError: OCI-22061: invalid format text [T
"
What I did to work around it, is on the select statement, do:
cur.execute( 'SELECT to_char(1) FROM DUAL' )
rows = cur.fetchall()
for row in rows:
val = int(row[0])
It's pretty ugly, but it works.
These types of errors went away when I upgraded to cx_Oracle 5.1. If the RPM doesn't install (like it happened for me on Red Hat 5.5) then you can usually rpm2cpio the file, take the cx_Oracle.so and put it into your python site-packages directory.
A work-around is putting time.sleep(1) before cursor.fetchone():
...
cursor.execute("SELECT DELETED FROM SERVICEORDER WHERE ORDERID='TEST'")
time.sleep(1)
print(cursor.fetchone()[0])
I had the same error.
Commit helped me:
conn = cx_Oracle.connect(...)
...
cursor.execute()
conn.commit()
Related
I´m Learning Coding and the Error Message from the Debugging confuse me a bit,
when i try to create a SQLlite Database with 11 statements, i have two different Errors.
here my Code:
import sqlite3
connection = sqlite3.connect("wtime1.db")
cursor = connection.cursor()
date = ("31.10.2022")
p_unit = ("MMO")
equip = ("D014-K-00001")
report_prio = ("1")
order_prio = ("2")
job = ("Oel wechsel")
w_time = ("120")
fte = ("2")
reason = ("Kein Oel vorhanden")
cause = ("MAR 2")
solved = ("Erledigt")
mar2_list = ([date, p_unit, equip, report_prio, order_prio, job, w_time, fte, reason, cause, solved])
cursor.execute("create table if not exists mar21 (DATE integer, P_UNIT text, EQUIP text, REPORT_PRIO text, ORDER_PRIO text, JOB text, W_TIME integer, FTE integer, REASON text, CAUSE text, SOLVED text)")
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
the first Error:
Incorrect number of bindings supplied. The current statement uses 11, and there are 10 supplied.
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
Okay i found in my search i need one more comma at the end of the Values
when i set the comma like this
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i have a syntax error
near ")": syntax error
File "C:\Users\andre\PycharmProjects\Wartezeiten\db_test.py", line 26, in <module>
cursor.executemany("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?,)", mar2_list)
i think i´m running a wrong way with the "insert values" line!
since you have one record use execute instead of executemany
cursor.execute("insert into mar21 values (?,?,?,?,?,?,?,?,?,?,?)", mar2_list)
my sql commands are working for instance to truncate table - but my load data command isn't actually inserting any records - how can I confirm py is reading my input file correctly or at all?
cursor.execute("LOAD DATA LOCAL INFILE '/home/user/mongo_exported_users.csv' INTO TABLE tbl.users IGNORE 1 LINES")
row_count = cursor.rowcount
for i in range(row_count):
line = cursor.fetchone()
print(line)
mydb.close()
print("Done")
The output of the fetchone is just None for all rows so IDK whats going on!
MySQL transactions have to be managed by commit. add the below line before closing the connection.
mydb.commit()
or
you can make autocommit just after the connection as shown below
mydb.autocommit = true
This should do the job
I'm trying to add all the file names and last modification time for files in a specific directory to a database in two different columns. This is code I have:
def getlist (self):
dbinput = self.txt_dest.get()
conn = sqlite3.connect ('dirdrill.db')
for files in os.listdir(dbinput):
for modtime in os.path.getmtime(dbinput):
with conn:
cur = conn.cursor()
cur.execute("INSERT INTO tbl_files(col_filename, col_modinfo) values (?,?)", files, modtime)
conn.commit()
conn.close()
getinfo(self)
I am getting the following error:
File "C:\Users\Ryan\Documents\GitHub\Tech-Academy-Projects\Python\dir_drill\dirdrill_func.py", line 69, in getlist
for modtime in os.path.getmtime(dbinput):
TypeError: 'float' object is not iterable
Do I need to convert the numbers that getmtime() returns into a human friendly format so that it is not a float? If so, how? Or should I be structuring the function a different way?
EDIT:
Thanks to some other help I found out that I just needed to change one line to modinfo = os.path.getmtime(dbinput). Did that and it solved the float error. However now it says that I am offering too many arguments, max 2 and I have 3, even thought I only see two. Onto the next bug... :-)
Found the answer to the original question and the additional error I discovered.
In the original code I needed to change the following:
for modtime in os.path.getmtime(dbinput):
to:
modtime = os.path.getmtime(dbinput)
For the follow up error related to too many parameters, files and modinfo needed to be wrapped in parenthesis like so:
cur.execute("INSERT INTO tbl_files(col_filename, col_modinfo) values (?,?)", (files, modtime))
Hopes this helps anyone else experiencing the same error.
In a Python2.7 script, the following gave me an error, I can't figure out why:
import psycopg2
conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()
curs.execute("CREATE TABLE newtable;")
The error looks like:
Traceback (most recent call last):
File "<ipython-input-17-f4ba0186c40c>", line 1, in <module>
curs.execute("CREATE TABLE newtable;")
ProgrammingError: syntax error at or near ";"
LINE 1: CREATE TABLE newtable;
Any SELECT statement works perfectly well on the other hand. For example:
curs.execute("SELECT * FROM table1 LIMIT 0;")
works like a charm.
CREATE TABLE newtable; is not the correct syntax to create a new table. You need to define some columns.
CREATE TABLE newtable (
foo INTEGER,
bar TEXT
);
See the CREATE TABLE docs for more info.
I am trying to create a database from a cif file, and getting an odd error:
import sqlite3 as sq
sqlfile = "mats.db"
tabnm = "elems"
id_col = "Properties"
val_col = "Value"
conn = sq.connect(sqlfile)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS Trial
(Properties text, Name text, Phase text, AbM text, AbB text, Cpre text)''')
lists = []
filename = "/var/tmp/1101142.cif"
fullparams=["_journal_coden_ASTM" , "_journal_issue", "_journal_name_full"
,"_journal_page_first","_journal_page_last","_journal_paper_doi"
,"_journal_volume","_journal_year","_chemical_formula_sum"
,"_chemical_formula_weight","_space_group_IT_number","_symmetry_cell_setting"
,"_symmetry_space_group_name_Hall","_symmetry_space_group_name_H-M ","_atom_sites_solution_primary"
,"_atom_sites_solution_secondary ","_audit_creation_method","_cell_angle_alpha"
,"_cell_angle_beta","_cell_angle_gamma","_cell_formula_units_Z"
,"_cell_length_a","_cell_length_b","_cell_length_c"
,"_cell_measurement_reflns_used","_cell_measurement_temperature","_cell_measurement_theta_max"
,"_cell_measurement_theta_min","_cell_volume"]
with open(filename, "r") as cif:
for line in cif:
for j in range(6):
if line.startswith(fullparams[j]):
# print(line)
lists.append(line.split()[-1])
print(lists)
c.executemany("INSERT INTO Trial VALUES(?, ?, ?, ?, ?, ?)",lists)
conn.commit()
While I have made sure the number is equal, I am still getting error:
python3 parse_cif.py
['CMATEX', '7', "Materials'", '1745', '1752', '10.1021/cm0513738']
Traceback (most recent call last):
File "parse_cif.py", line 36, in <module>
c.executemany("INSERT INTO Trial VALUES(?, ?, ?, ?, ?, ?)",lists)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 6, and there are 1 supplied.
I have no idea how it is counting supplied value 1. I have seen similar question already asked as:Python 3 SQLite3 - Incorrect number of bindings, sqlite3 - Incorrect number of bindings supplied but cant solve my problem.
Kindly help.
executemany() executes the same statement multiple. So it does not expect a list of paramters, but a list containing multiple parameter lists, one for each execution.
In this case 'CMATEX' looks like a list containing six characters, so it executes just fine. But the next list, '7', contains only a single value; this is the error you get.
To insert a single row, use execute() instead.