python peewee You have an error in your SQL syntax; - python

I have a model
for save telegram bot info
class Bots(BaseModel):
bot_token = CharField(max_length=500, unique=True)
username = CharField(max_length=32, null=True)
admin_id = ForeignKeyField(Users, Users.user_id,
on_delete='CASCADE')
#classmethod
def insert_bot(cls, token, username, admin_id):
q = cls.insert(bot_token=token, username=username,
admin_id=admin_id).on_conflict_ignore(ignore=True)
q.execute()
return q
If we print q
We receive this query
INSERT IGNORE INTO `bots` (`bot_token`, `username`, `admin_id`) VALUES ('5500232067:AAHkXEzVHb-9Vvsw4bAKWfFZatQyQhVfIco','vdp_ka_1234_bot', 5366819345)
If we execute this query in mysql shell, it will be executed without error
But I get error in peewee
error message
During handling of the above exception, another exception occurred:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\projects\python-projrct\upload_file\venv\Lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "D:\projects\python-projrct\upload_file\venv\Lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "D:\projects\python-projrct\upload_file\venv\Lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
peewee.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 'IGNORE INTO `bots` (`bot_token`, `username`, `admin_id`) VALUES ('5500232067:AAH' at line 1")

Seems to be working well for me:
db = MySQLDatabase('peewee_test')
class Reg(db.Model):
key = CharField(unique=True)
db.create_tables([Reg])
Reg.create(key='k1')
Reg.insert(key='k1').on_conflict_ignore().execute()
print(len(Reg))
This, correctly, prints "1" with no errors.

Related

pymysql error attempting to run query : sqlalchemy.exc.ProgrammingError

I am running a query using pymysql and passing a string as a parameter for the where clause condition. Code and Error Traceback below:
import pandas as pd
# mysql connection
import pymysql
from sqlalchemy import create_engine
user = 'user'
pwd = 'xxxxx'
host = 'x.com'
port = 3306
database = 'dbname'
engine = create_engine("mysql+pymysql://{}:{}#{}/{}".format(user,pwd,host,database))
con = engine.connect()
c = 'Phoenix, AZ'
query = '''
select * from schema_name.table1
where city = {};
'''.format(c)
df = pd.read_sql(query, con)
Traceback:
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
sqlalchemy.exc.ProgrammingError: (pymysql.err.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 ', AZ' at line 2")
The value needs to be quoted. It's best to let the database connector do it, to protect against injection attacks:
query = '''
select * from schema_name.table1
where city = %s;'''
df = pd.read_sql(query, con, params=[c])

PYMYSQL ERROR pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax ")

Here is the full error
Traceback (most recent call last):
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/test.py", line 26, in <module>
handler()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/test.py", line 17, in handler
cursor.execute('SELECT * FROM Reads')
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/cursors.py", line 148, in execute
result = self._query(query)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/cursors.py", line 310, in _query
conn.query(q)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "Desktop/Work/RDS_LAMDA_Stuff/RDS_Node_Stuff/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.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 'Reads' at line 1")
For context here is my code
from multiprocessing import connection
import pymysql
from pymysql.cursors import Cursor
# RDS config
endpoint = '********'
username = '********'
password = '********'
database_name = '*********'
#connection config
connection = pymysql.connect(host=endpoint,user=username,passwd=password,db=database_name)
def handler():
cursor = connection.cursor()
cursor.execute('SELECT * FROM Reads')
rows = cursor.fetchall()
for row in rows:
print("{0} {1} {2} {3}".format(row[0], row[1], row[2], row[3]))
handler()
I have 2 other tables in my database which work fine when i query them however this table seems to be the only one causing an error.
Feel free to ask for more if this is too vague
It's worth checking manual in cases like this - and Reads is a reserved word therefore must be backticked - better still don't use reserved words or you will forever have to remember to backtick in code..

Error using pymssql when creating database users in SQL Server

I am getting the below error whenever I am trying to create a new user on a database.
Traceback (most recent call last):
File "src\pymssql\_pymssql.pyx", line 460, in pymssql._pymssql.Cursor.execute
File "src\pymssql\_mssql.pyx", line 1104, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql\_mssql.pyx", line 1135, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql\_mssql.pyx", line 1268, in pymssql._mssql.MSSQLConnection.format_and_run_query
File "src\pymssql\_mssql.pyx", line 1806, in pymssql._mssql.check_cancel_and_raise
File "src\pymssql\_mssql.pyx", line 1852, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (102, b"Incorrect syntax near 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_sqlserver.py", line 60, in <module>
createUsers(row[0][:-1], target_server, target_database)
File "test_sqlserver.py", line 44, in createUsers
cursor.execute('%s', sqlStatement)
File "src\pymssql\_pymssql.pyx", line 475, in pymssql._pymssql.Cursor.execute
pymssql._pymssql.ProgrammingError: (102, b"Incorrect syntax near 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
Below is my code currently.
def createUsers(sqlStatement, server, database):
conn = pymssql.connect(server=server, database=database)
cursor = conn.cursor()
cursor.execute('%s', sqlStatement)
target_server = 'MYServer'
target_database = 'MYDatabase'
sqlStatement = 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'
createUsers(sqlStatement, target_server, target_database)
I am not sure why I am getting this error as I can execute the SQL statement directly on the database without any issues. And I can also use pymssql to query information from the database. But whenever I try to create a new user on the database, I keep getting this error. Is anyone familiar with this?
Issue was resolved after changing cursor.execute statement to below
cursor.execute(sqlStatement)
I also had to add the below commit, otherwise the changes were not being seen on the database side.
conn.commit()

MYSQL Connector Python Issue | Select Query

I'm having a problem with this MySQL Query, how can I fix that?
valori = (message.from_user.id, message.from_user.username)
verifica = "SELECT * FROM utenti WHERE ID = %s, Username = %s"
cursor.execute(verifica, valori)
A sample of variable "valori":
(1062473636, 'Partizionare')
Error:
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 ' Username = 'Partizionare'' at line 1
Traceback (most recent call last):
File "/home/lello/.local/lib/python3.7/site-packages/pyrogram/dispatcher.py", line 217, in handler_worker
await handler.callback(self.client, *args)
File "/home/lello/Documents/Telegram/LelloDevBot/pyro.py", line 19, in start
cursor.execute(verifica, valori)
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
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 ' Username = 'Partizionare'' at line 1
There's no such thing as , in conditions, you mean AND.

Insert ERROR - mysql connector python 2.7

I am attempting to insert some sentiment analysis results (google cloud language API) into a mysql database. I am using the mysql connector.
import mysql.connector
from google.cloud import language
cnx = mysql.connector.connect(user='blahuser', password='Blahpw',
host='BlahIP',
database='FeedbackDB')
cursor = cnx.cursor(buffered=True)
CoreSQL = ("SELECT ResID, TextResp FROM Response")
cursor.execute(CoreSQL)
client = language.Client()
for row in cursor:
document = client.document_from_text(row[1])
sent_analysis = document.analyze_sentiment()
sentiment = sent_analysis.sentiment
annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
print(row[0], sentiment.score, sentiment.magnitude)
ResID_ =row[0]
PhraseSent_ = sentiment.score
PhraseMag_ = sentiment.magnitude
SQLInsertCmd = ("INSERT INTO PhraseAnalysis (ResID, PhraseSent, PhraseMag), VALUES (%s,%s,%s)");
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
cnx.commit()
cursor.close()
cnx.close()
The error I get indicates I have an issue with my INSERT statement :
python tm16.py
(1, -0.4, 2.2)
Traceback (most recent call last):
File "tm16.py", line 27, in <module>
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 559, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 494, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 396, in _handle_result
raise errors.get_exception(packet)
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 ' VALUES (1,-0.4,2.2)' at line 1
There are lots of INSERT examples online, but I haven't be able to resolve. New to coding- no doubt something simple. Can someone point out where I am going wrong?
Mike
You have an unnecessary comma after the end of the fields list.

Categories