AttributeError: 'MySQLCursor' object has no attribute 'commit' - python

def fillblast(sequentie, titel_lijst, score_lijst, e_lijst, iden_lijst, pos_lijst, gaps_lijst):
conn = mysql.connector.connect(host = "ithurtswhenip.nl", user = "pg2", password = "pg2", database= "pg2", port= "3307")
cursor = conn.cursor()
Blast = 1000
for i in range(0,len(titel_lijst)):
Blast =+ 2
cursor.execute("INSERT INTO `pg2`.`Blast` (`Blast_id`, `Blast_seq`, `Blast_titel`, `Blast_score`, `Blast_E`, `Blast_gaps`, `Blast_pos`, `Blast_iden`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (Blast, sequentie[i] ,titel_lijst[i], score_lijst[i], e_lijst[i], iden_lijst[i], pos_lijst[i], gaps_lijst[i]))
print("1 record toegevoegd")
cursor.commit()
cursor.close()
conn.close()
I get the following error:
AttributeError: 'MySQLCursor' object has no attribute 'commit'
How does it come, and where does it go wrong?
I try to connect with MySQLWorkbench.
EDIT:
Now I get the following error:
mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Because you can not commit a cursor! you must commit the connection.
# cursor.commit() --> This is wrong!
conn.commit() # This is right
Check the docs...

While fixing some legacy code (that apparently hasn't been working for a couple of years, so users stopped trying to use it), we ran into the same error, using the MySQL-python package in Django. Using the suggestions on this and other answers however resulted in a different error, on account of it occurring within the Django ORM:
django.db.transaction.TransactionManagementError: This code isn't
under transaction management
So for those who run into this error after using conn.commit() instead of cursor.commit(), you may be able to use enter_transaction_management and leave_transaction_management (note that this was for Django 1.4.6 and MySQL-python 1.2.5; I may have to update this once we get the Django upgrade completed):
try:
conn.enter_transaction_management()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except DatabaseError as e:
cursor.rollback()
log.warning('log warning here')
# Handle other exceptions here.
finally:
if cursor:
cursor.close()
conn.leave_transaction_management()

Related

error using python.connector by select ... where ... command

When I run this function some error occurs, but I have no idea what's wrong.
def insertVariblesIntoTable(newepc, newtimestamp):
try:
connection = mysql.connector.connect(host='localhost',
database='myDB',
user='root',
password='root')
cursor = connection.cursor()
mySql_insert_query = """INSERT INTO myTB(epc,time_stamp)
SELECT newepc,newtimestamp
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTB
WHERE epc=newepc
AND time_stamp>NOW()-INTERVAL 1 MINUTE )"""
cursor.execute(mySql_insert_query)
connection.commit()
print("Record inserted successfully into myTB table")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
# print("MySQL connection is closed")
error:
Failed to insert into MySQL table 1054 (42S22): Unknown column 'newepc' in 'field list'
As far as I can tell, you're trying to access a column named "newepc" which doesn't exist.
This happens, because you're not escaping the variable "newepc" in your select query, mySql doesn't know it should be a variable.. you can try f-Strings or just normal concatination.

How to insert variable to mysql database with python? "You have an error in your SQL syntax"

I am trying to insert one variable to mysql database with python. But I have syntax error.. Can You help me please? :)
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='Xiaomi_Temp',
user='user',
password='pass')
cursor = connection.cursor()
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%d) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into table")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
I have variable batt and it has integer value.
My output is:
Failed to insert record into table 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%d)' at line 1
MySQL connection is closed
As the whole query needs to be in a string format while execution of query so %s should be used instead of %d which can be done as follows,
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%s) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)

Accessing MySQL from Python 2.7: ProgrammingError: 1045 (28000)

I am having difficulties connecting to a MySQL database using Python 2.7. The error I'm getting is
ProgrammingError: 1045 (28000): Access denied for user
'tommyan'#'localhost' (using password: YES)
I know similar questions exist, but none of those were helpful to me. My code is below, thanks in advance.
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="tommyan",
passwd="######",
database="mydatabase"
)
mycursor = mbdb.cursor()
sql = "INSERT INTO places (name, desc) VALUES (%s, %s)"
val = ("Natinal gallery", "Housing masterpieces by painters including van Gogh,
Renoir, da Vinci and Michelangelo")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

Getting more info from python sqlite exceptions

I'm using python's builtin sqlite3 DB module.
While inserting objects to my DB tables, following sqlite exception raised:
"PRIMARY KEY must be unique"
As there are different insert methods for each object, I can't say for sure in which table does it failed:
import sqlite3
...
class SomeObject1:
....
def _insert_some_object1(self, db_object):
self._cursor.execute('insert into %s values (?,?,?)' % TABLE_NAME,
(db_oject.v1, db_object.v2, db_object_v3,))
Exception got caught in main() by except Exception as e:, so it's only info I've got.
I would want to know in which table insertion failed, value that failed, etc...
What's the right way to get the most info from sqlite exceptions?
Thanks
I think this really all depends on what you are using to connect to the database. Each module will display different errors.
I personally use sqlalchemy, and it gives you detailed errors. Here is an example to show what I mean (note: this is just an example, I personally do not support inline sql):
import sqlalchemy
connection = sqlalchemy.create_engine('sqlite:///mydb.db')
cursor = connection.connect()
query = "INSERT INTO my_table (id, name) values(1, 'test');"
cursor.execute(query)
And the error that is returned:
sqlalchemy.exc.IntegrityError: (IntegrityError) PRIMARY KEY must be unique "INSERT INTO my_table (id, name) values(1, 'test');" ()
As far as core sqlite3 module, I don't believe it will show the query that was executed. If you don't use a module such as sqlalchemy, then you will need to handle and show the error yourself. Take a look at this as example:
import sqlite3
def execute(query):
try:
conn = sqlite3.connect('mydb.db')
c = conn.cursor()
c.execute(query)
conn.commit()
except Exception as err:
print('Query Failed: %s\nError: %s' % (query, str(err)))
finally:
conn.close()
execute("INSERT INTO my_table (id, name) values(1, 'test');")
And the output on error:
Query Failed: INSERT INTO weapon (id, name) values(1, 'test');
Error: PRIMARY KEY must be unique
I have seen some code like (sqlite3 in python)
try:
conn = sqlite3.connect('mydb.db')
c = conn.cursor()
c.execute(query)
conn.commit()
except sqlite3.Error as err:
print('Sql error: %s' % (' '.join(err.args)))
print("Exception class is: ", err.__class__)

Insert into SQLite file Python - does not work

I have a simple database application in Python with SQLite. I wrote a simple program to create database and insert into some values. However, database is created, but new values are not inserted, and I don't know why:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
def CreateTable():
try:
connection = lite.connect(':memory:')
with connection:
cursor = connection.cursor()
sql = 'CREATE TABLE IF NOT EXISTS Authors' + '(ID INT PRIMARY KEY NOT NULL, FIRSTNAME TEXT, LASTNAME TEXT, EMAIL TEXT)'
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
def Insert(firstname, lastname, email) :
try:
connection = lite.connect('authors.sql')
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, %s, %s, %s)" % (firstname, lastname, email)
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
CreateTable()
Insert('Tibby', 'Molko', 'tibby.molko#yahoo.co.uk')
You are not calling commit on your connection. You should also not write to the database file yourself, the database engine is writing to the file.
Try to go through the first few examples in sqlite documentation, it should be clear then.
You have misunderstood what connection.iterdump() is for. You are creating SQL text, instructions for SQLite to execute again at a later date. It is not the database itself. If all you wanted was to output SQL statements you can just write your SQL statements directly, there is little point in passing it through SQLite first.
You also cannot 'connect' SQLite to the text file with SQL statements; you'd have to load those statements as text and re-play them all. That's not what I think you wanted however.
You can connect to an existing database to insert additional rows. Each time you want to have add data, just connect:
def CreateTable():
connection = lite.connect('authors.db')
try:
with connection as:
cursor = connection.cursor()
sql = '''\
CREATE TABLE IF NOT EXISTS Authors (
ID INT PRIMARY KEY NOT NULL,
FIRSTNAME TEXT,
LASTNAME TEXT,
EMAIL TEXT)
'''
cursor.execute(sql)
finally:
connection.close()
def Insert(firstname, lastname, email) :
connection = lite.connect('authors.db')
try:
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, ?, ?, ?)"
cursor.execute(sql, (firstname, lastname, email))
finally:
connection.close()
Note that using the connection as a context manager already ensures that the transaction is either committed or rolled back, depending on there being an exception.
On the whole, you want to be informed of exceptions here; if you cannot connect to the database you'd want to know about it. I simplified the connection handling as such. Closing a connection auto-closes any remaining cursors.
Last but far from least, I switched your insertion to using SQL parameters. Never use string interpolation where parameters can be used instead. Using parameters makes it possible for the database to cache statement parse results and most of all prevents SQL injection attacks.
You cannot connect to a text file with sql commands.
sqlite3.connect expects or creates a binary file.
You didnt commit it.For writing into database, it should be committed.For read (select) operations,not needed.
try:
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, ?, ?, ?)"
cursor.execute(sql, (firstname, lastname, email))
connection.commit() # or cursor.commit()
finally:
connection.close()

Categories

Resources