How to execute database insert do MariaDB using Python? - python

I have a problem inserting data into my database table. I'm using Python and MariaDB. Connection to database is open and tested, I'm able to query the database, but I can't nail the insert syntax. I've found two ways, but neither work.
insert = (
"INSERT INTO ksiazka (ISBN, tytul, autor, rok_wydania, ilosc stron)"
"VALUES (%s,%s,%s,%s,%s)"
)
dane = (ISBN, tytul, autor, rok_wydania, ilosc_stron)
cursor.execute(insert, dane)
or this way:
cursor.execute("INSERT INTO ksiazka (ISBN, tytul, autor, rok_wydania, ilosc stron) VALUES (%s,%s,%s,%s,%s)", (ISBN, tytul, autor, rok_wydania, ilosc_stron))
When executing I get this error:
Traceback (most recent call last): File
"C:\Users\jakub\AppData\Local\Programs\Python\Python36\lib\site-packages\mysql\connector\connection_cext.py",
line 377, in cmd_query
raw_as_string=raw_as_string)
_mysql_connector.MySQLInterfaceError: 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 'stron)VALUES
('12345678','wertvfdg','3','1243','213')' at line 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:/Users/jakub/PycharmProjects/biblioteka/sql_connector.py", line 57,
in
cursor.execute(insert, dane) File "C:\Users\jakub\AppData\Local\Programs\Python\Python36\lib\site-packages\mysql\connector\cursor_cext.py",
line 264, in execute
raw_as_string=self._raw_as_string) File "C:\Users\jakub\AppData\Local\Programs\Python\Python36\lib\site-packages\mysql\connector\connection_cext.py",
line 380, in cmd_query
sqlstate=exc.sqlstate) mysql.connector.errors.ProgrammingError: 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 'stron)VALUES ('12345678','wertvfdg','3','1243','213')' at
line 1

If your column name has a space in it, then it needs special handling and you must escape it:
INSERT INTO ksiazka (ISBN, tytul, autor, rok_wydania, `ilosc stron`) ...
This is why spaces in column names are annoying and should be avoided.

Related

I'm having trouble with an SQL syntax error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to add data to a table collected on a tkinter GUI. This error keeps coming up:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\xande\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py", line 489, in cmd_query
raw_as_string=raw_as_string)
_mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Rank,Email,Phone) VALUES(5509,'mandy123','password123','Mike','Andy','MJR','mand' at line 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xande\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\xande\OneDrive\Desktop\School\YR 14\CCF program\CCF code.py", line 146, in addldrsubmit
mycursor.execute(insertSQL,(LID,str(lunentry),str(lpwentry),str(lfnentry),str(lsnentry),str(lrankentry),str(lemailfullentry),lphoneentry,))
File "C:\Users\xande\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py", line 266, in execute
raw_as_string=self._raw_as_string)
File "C:\Users\xande\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py", line 492, in cmd_query
sqlstate=exc.sqlstate)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Rank,Email,Phone) VALUES(5509,'mandy123','password123','Mike','Andy','MJR','mand' at line 1
The code I'm using is:
import mysql.connector
if True:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="abarclay172",
database="rbaiccf"
)
mycursor=mydb.cursor()
LID = random.randint(1000,9999)
lunentry = lunentrye.get()
lpwentry = lpwentrye.get()
lfnentry = lfnentrye.get()
lsnentry = lsnentrye.get()
lrankentry = addldrranke.get()
lemailentry = lemailentrye.get()
lemailaddressentry = addldremailaddresse.get()
lemailfullentry = lemailentry + lemailaddressentry
lphoneentry = "+44" + lphoneentrye.get()
insertSQL="""INSERT INTO leader(leaderID,Username,Password,Forename,Surname,Rank,Email,Phone) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"""
mycursor.execute(insertSQL,(LID,str(lunentry),str(lpwentry),str(lfnentry),str(lsnentry),str(lrankentry),str(lemailfullentry),lphoneentry,))
mydb.commit()
From the description you have provided, I guess it is the usage of RANK as a column name. It is a reserved keyword. You could try this solution - using backticks.
But if there is something else going on, you shold provide more info, as stated in comments. Table definition, full SQL, you are trying to execute.

"not a query" exception while executing query using cx_Oracle in python

I am trying to connect to oracle database and execute a query using cx_Oracle in python with following code
import cx_Oracle
mobileNumber='1234567890'
dbHost='some_value'
dbPortNumber='some_value'
dbUsername='some_value'
dbPasswd='some_value'
dsn_tns = cx_Oracle.makedsn(dbHost, dbPortNumber, service_name='ORCL')
conn = cx_Oracle.connect(user=dbUsername, password=dbPasswd, dsn=dsn_tns)
cur=conn.cursor()
query='insert into table_name values ((select max(ID)+1 from table_name),"sms","'+ mobileNumber + '")'
cur.execute(query)
res=cur.fetchall()
print (res)
But I am getting following exception when running this code
Traceback (most recent call last):
File "script.py", line 16, in <module>
result=cur.fetchall()
cx_Oracle.InterfaceError: not a query
When printing the value of variable query I am getting following
insert into table_name values ((select max(ID)+1 from table_name),"sms","1234567890")

Error with Sqllite3 reading .sql file

So I've got a .sql file that I want to build over to a .db file for sqllite3, but I'm getting a
sqlite3.OperationalError: near "ENGINE": syntax error
Any ideas why? Any help is appreciated.
import sqlite3
conn = sqlite3.connect('newdatabase.db')
f = open('olddatabase.sql','r')
sql = f.read()
conn.executescript(sql)
conn.close()
OUTPUT:
Traceback (most recent call last):
File "deleteme.py", line 6, in
conn.executescript(sql)
sqlite3.OperationalError: near "ENGINE": syntax error
(program exited with code: 1)
Divining based on ENGINE, you have a .sql file dumped by MySQL (CREATE TABLE ... ENGINE=InnoDB or similar), so it contains MySQL-specific extensions.
You'll have to either edit the .sql file to conform to SQLite's standards or figure out a way to convert it automatically to a more standard sequence of SQL instructions.

1064, "You have an error in your SQL syntax

Here is the error:
gutschy#kiste:~/pizza/pizza_daten$ python datenimport3.py
Traceback (most recent call last):
File "datenimport3.py", line 20, in <module>
")
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Adressliste_forum1_v4.csv' INTO TABLE pizzeria_table FIE' at line 1")
gutschy#kiste:~/pizza/pizza_daten$
Here the datenimport3.py
#!/usr/bin/python
#-*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'passw', 'pizzadb2');
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute(" 'Adressliste_forum1_v4.csv'\
INTO TABLE pizzeria_table \
FIELDS TERMINATED BY ',' \
ENCLOSED BY '\"' \
LINES TERMINATED BY '\\n' \
IGNORE 1 LINES \
(laden_name, vorwahl, telenr1, strasse, hausnr, \
ort, linkname1, linkname2, linkname3, forum_link, \
link2, link3, banner) \
")
Four month ago it works all fine, than I killed my debian 7 and now I'm on to bring it in the same way like before. I've add the last field "banner" new but I've done noting more.
You can sort through all that traceback chaff by looking for this:
...for the right syntax to use near ''Adressliste_forum1_v4.csv' INTO ...
On a 1064 error, MySQL presents, right after "use near", your statement starting with the place where its parse error was found.
Now, should not your statement start with
LOAD DATA INFILE 'Adressliste_forum1_v4.csv' INTO ...
?

delete python mysql issues

In order to delete the table named cars I created in python-mysql , I do
import MySQLdb as mdb
con = mdb.connect('localhost', 'priceapi', 'data', 'carpricedb');
cur = con.cursor()
cur.execute("DELETE FROM cars");
con.commit()
con.close()
But I get an error like this
Traceback (most recent call last):
File "delete.py", line 4, in <module>
cur.execute("DELETE FROM cars");
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction')
My Table only has 78 rows. I also tried truncating the table. The result is the same.
I tried doing it directly in mysql , but then it doesnt execute the command and I had to kill it using Control+C. I searched a lot for the last 1 hour, but could not find the solution .
Any help please ?
Delete is very very very very slow SQL operation and i guess that the table is huge so it takes a lot of time to finish. It's best to drop and recreate a table if you want it clear (truncate is a 2nd best option).
It is also possible that some query is locking your table, you can clear that lock off by stopping and starting mysql again (or by finding which query is doing that and kill it).

Categories