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

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.

Related

Databases Removing a Single Element SDK Error (Multiple WHEREs)

I am trying to remove a single element from my database using an SDK. I keep getting the following error and I don't know how to fix it:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/Users/jasonsilla/Desktop/Code/Python/Book_GUI_Program/main.py", line 25, in remove_from_list
if booksSDK.delete_book(book):
File "/Users/jasonsilla/Desktop/Code/Python/Book_GUI_Program/booksSDK.py", line 52, in delete_book
c.execute("DELETE FROM books WHERE title=?, pages=?", (book.title, book.pages))
sqlite3.OperationalError: near ",": syntax error
The code for the SDK to remove an element is as follows:
def delete_book(book):
c = cursor()
with c.connection:
c.execute("DELETE FROM books WHERE title=?, pages=?", (book.title, book.pages))
row_count = c.rowcount
c.connection.close()
return row_count
My question is why am I getting this error. I don't understand this, so if anyone can please help me, I believe that either the error in the code is in the:
c.execute("DELETE FROM books WHERE title=?, (<-) pages=?", (book.title, (<- or here) book.pages))
Thank you!!!
The problem is in the 1st arrow:
title=?, (<- here) pages=?
Instead of the comma, you want to put AND. This eliminates the error. Hopefully I helped!!!

How to execute database insert do MariaDB using 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.

to_sql - "cannot use a string pattern on a byte-like object"

I am trying to use pandas, sqlalchemy and pypyodbc in order to write my dataframe (df2) to a table in my sql database. I have successfully connected to the database with pypyodbc. However, when I try to use the engine with to_sql it throws the error in the title. I think I'm missing something in the urllib section when the engine creation string is parsed.
Here is my code snippet:
connStr = "Driver=SQL Server Native Client 10.0; Server=Sname-L\SQLEXPRESS;database=DBname;trusted_connection=yes;"
connEncodedStr = urllib.parse.quote_plus(connStr)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect={}".format(connEncodedStr),module=pypyodbc,echo=True)
df2.to_sql('db_table2', engine, if_exists='replace')
print(engine)
result:
Engine(mssql+pyodbc:///?odbc_connect=Driver=SQL Server Native Client 10.0; Server=Sname-L\SQLEXPRESS;database=DBname;trusted_connection=yes;)
Here is the traceback:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\s
qlalchemy\pool.py", line 1122, in _do_get
return self._pool.get(wait, self._timeout)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\s
qlalchemy\util\queue.py", line 145, in get
raise Empty
sqlalchemy.util.queue.Empty
However, this also happened:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "noaadatamanip_datafram.py", line 50, in <module>
df2.to_sql('db_table2', engine, if_exists='replace')
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\p
andas\core\generic.py", line 1201, in to_sql
chunksize=chunksize, dtype=dtype)
The above code went on for a lot of lines and returned the error in the title. Let me know if posting the whole thing will be helpful.
Sorry in advance, my error handling skills are very low.

[Python]:phoenixdb.errors.ProgrammingError: ("Syntax error. Unexpected char: '!'", 601, '42P00', None)

I am using a python module called phoenixdb to access phoenix which is SQL wrapper to query over HBase.
Here is my code snippet:-
import phoenixdb
database_url = 'http://localhost:8765/'
conn = phoenixdb.connect(database_url, autocommit=True)
cursor = conn.cursor()
cursor.execute("!table")
print cursor.fetchall()
cursor.close()
The phoenix query to list all the schemes and tables is !table or !tables.
But when I try passing the same in the execute function as shown above, I get the following error:-
Traceback (most recent call last):
File "phoenix_hbase.py", line 7, in <module>
cursor.execute("!table")
File "build/bdist.linux-x86_64/egg/phoenixdb/cursor.py", line 242, in execute
File "build/bdist.linux-x86_64/egg/phoenixdb/avatica.py", line 345, in prepareAndExecute
File "build/bdist.linux-x86_64/egg/phoenixdb/avatica.py", line 184, in _apply
File "build/bdist.linux-x86_64/egg/phoenixdb/avatica.py", line 90, in parse_error_page
phoenixdb.errors.ProgrammingError: ("Syntax error. Unexpected char: '!'", 601, '42P00', None)
Funny part is when I try to passing a different query, for example a select query, then script gets executed and produces result just fine.
Query:cursor.execute("select * from CARETESTING.EDR_BIN_SOURCE_3600_EDR_FLOW_SUBS_TOTAL limit 1")
Result:
[[2045,1023,4567]]
Is there any other format for passing !table which is equivalent to show tables in phoenixdb library's execute function which I am missing?
I tried looking up on the internet but unfortunately haven't come across anything helpful so far.
Thanks
!tables is sqlline grammar that can not be parsed by JDBC interface.

Syntax for changing a python script from sqlite3 to mysql

I have a working python script which retrieves data from a sqlite3 db. I need to convert it to talk to a mysql db though, and here's the first line that is giving me grief:
PRODUCT_CODE_ID = "SELECT id FROM localsite_productcode WHERE localsite_productcode.product_code=?"
cur.execute(PRODUCT_CODE_ID,(product_code,))
When I try that with mysql I get the following error:
Traceback (most recent call last):
File "gen-csv.py", line 85, in <module>
cur.execute(PRODUCT_CODE_ID,(product_code,))
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 151, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
What am I doing wrong here?
I don't think the DB API for MySQL supports the ? as a place holder - just try %s instead.

Categories