Started learning mySQL and got stuck on why this command is not working. I had success with UPDATE commands and SELECT * outside the function so I am guess I am making a mistake in calling the function or perhaps the %s needs to be different... My google foo did not find anything so I hope you all can help me!
Thank you so much for looking!
CODE:
def CheckBalance(UserName, BetAmount): #checks to make sure they can afford the bet. Returns 0 for no 1 for yes
import mysql.connector
cnx = mysql.connector.connect(user='root', password='Password',
host='127.0.0.1',
database='crapsdatabase')
c = cnx.cursor()
BankRoll = c.execute("SELECT PlayerBank FROM player WHERE PlayerName = %s", UserName)
if(BankRoll < BetAmount) or (BetAmount < 0):
c.close()
return 0
if(BankRoll >= BetAmount):
c.close()
return 1
From our main program I import the UpdateDatabase and call it
from plugins.database.UpdateDatabase import UpdateBets
a = UpdateBets.CheckBalance("bob", 100)
print(a)
This gives the following error:
C:\python\python.exe C:/Users/Ray/Desktop/bot/plugins/CRAPS/CrapsUpdated.py
Traceback (most recent call last):
File "C:/Users/Ray/Desktop/bot/plugins/CRAPS/CrapsUpdated.py", line 3, in <module>
a = UpdateBets.CheckBalance("bob", 100)
File "C:\Users\Ray\Desktop\bot\plugins\database\UpdateDatabase.py", line 16, in CheckBalance
BankRoll = c.execute("SELECT PlayerBank FROM player WHERE PlayerName = %s", UserName)
File "C:\python\lib\site-packages\mysql\connector\cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\python\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\python\lib\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 MySQL server version for the right syntax to use near '%s' at line 1
You should escape string literal in the query with apostrophes, so it should be like this:
c.execute("SELECT PlayerBank FROM player WHERE PlayerName = '%s'", UserName)
Related
I am having an issue getting my UPDATE Query to work. I am using python 3.7 and building a gui using tkinter. I have an entry box that a user can select an Item by ID number, that auto-populates the following entry boxes and the user can then modify the entries. My error occurs when it comes time to save the changes. I have a button that calls a function save when clicked. see below
def save():
conn = mysql.connect(
host="localhost",
user="XXXX",
passwd="XXXX",
database="inventory")
c = conn.cursor()
a0 = selectent.get()
a1 = item.get()
a2 = asset_tag.get()
a3 = amount.get()
a4 = notes.get()
c.execute(""" UPDATE items SET
item = 'a1',
asset_tag = 'a2',
amount = 'a3',
notes = 'a4'
WHERE id = 'a0' """)
conn.commit()
conn.close()
I am self-teaching myself mySQL, and from what I have read about this error it appears that the error occurs when trying to compare a number and string in a WHERE clause. This makes sense since my traceback takes me to that line in my code.
Traceback (most recent call last):
File "C:\Users\mbrow\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\mbrow\AppData\Local\Programs\Python\Python37\Inventory3\editmodule.py", line 61, in save
WHERE id = 'a0' """)
File "C:\Users\mbrow\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\mbrow\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py", line 475, in cmd_query
sqlstate=exc.sqlstate)
mysql.connector.errors.DataError: 1292 (22007): Truncated incorrect DOUBLE value: 'a0'
Can someone explain this to me so I better understand what is going on?
I know amount is spelled wrong.
Use parameterized query and prepared statement
c.execute(""" UPDATE items SET
item = %s,
asset_tag = %s,
amount = %s,
notes = %s
WHERE id = %s """,(a1,a2,a3,a4,a0))
I'm having a heck of a time getting the mysql.connector module to work. I'd really like to find some accurate documentation on it. By hit and by miss, I have arrived here.
Traceback (most recent call last):
File "update_civicrm_address.py", line 80, in <module>
cursor.execute(mysql_select_query, address_id)
File "/home/ubuntu/.local/lib/python3.6/site-packages/mysql/connector/cursor.py", line 1210, in execute
msg="Incorrect number of arguments " \
mysql.connector.errors.ProgrammingError: 1210: Incorrect number of arguments executing prepared statement
Here is the program (it's a bit messy because I have tried so many things to get it to work). Aside from the fact that the update is not working at all, what is causing the error? There is only one parameter and it is accounted for.
import sys
import mysql.connector
import csv
import os
from mysql.connector import Error
from mysql.connector import errorcode
#Specify the import file
try:
inputCSV = 'geocoded_rhode_island_export.csv'
#Open the file and give it a handle
csvFile = open(inputCSV, 'r')
#Create a reader object for the input file
reader = csv.reader(csvFile, delimiter = ',')
except IOError as e:
print("The input file ", inputCSV, " was not found", e)
exit()
try:
conn = mysql.connector.connect(host='localhost',
database='wordpress',
user='wp_user',
password='secret!',
use_pure=True)
cursor = conn.cursor(prepared=True)
except mysql.connector.Error as error:
print( "Failed to connect to database: {}".format(error))
exit()
try:
record_count = 0
for row in reader:
contact_id,address_id,last_name, first_name, middle_name, longitude, latitude = row
print(row)
#Update single record now
print(address_id)
cursor.execute(
"""
update civicrm_address
set
geo_code_1 = %s,
geo_code_2 = %s
where
id = %s
and
location_type_id = %s
""",
(longitude, latitude, address_id, 6)
)
conn.commit
print(cursor.rowcount)
print("Record updated successfully")
mysql_select_query = """
select
id,
geo_code_1,
geo_code_2
from
civicrm_address
where
id = %s
"""
input = (address_id)
cursor.execute(mysql_select_query, address_id)
record = cursor.fetchone()
print(record)
record_count = record_count + 1
finally:
print(record_count, " records updated")
#closing database connection.
if(conn.is_connected()):
conn.close()
print("connection is closed")
The is an error in the code
conn.commit
should be
conn.commit()
The connection is fine, but the query sentence seems problematic.
query1 = """SELECT * FROM `DATABASE` WHERE `coin` = 'LTC'"""
query2 = """SELECT * FROM `DATABASE` WHERE `coin` = 'LTC' AND `date` > '2019-01-01 15:06:23'"""
And then
import pandas as pd
result = pd.read_sql(query, connection)
It works perfectly fine with query1 but gives such error for query2:
result = pd.read_sql(query, connection)
Traceback (most recent call last):
File "<ipython-input-25-c7c27cfd9a6b>", line 1, in <module>
result = pd.read_sql(query, connection)
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pandas\io\sql.py", line 381, in read_sql
chunksize=chunksize)
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1413, in read_query
cursor = self.execute(*args)
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1386, in execute
raise_with_traceback(ex)
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pandas\compat\__init__.py", line 404, in raise_with_traceback
raise exc.with_traceback(traceback)
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1382, in execute
self.con.rollback()
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pymysql\connections.py", line 808, in rollback
self._execute_command(COMMAND.COM_QUERY, "ROLLBACK")
File "C:\Users\luzhe\Anaconda3\lib\site-packages\pymysql\connections.py", line 1122, in _execute_command
raise err.InterfaceError("(0, '')")
DatabaseError: Execution failed on sql: SELECT * FROM `DATABASE` WHERE `coin` = 'LTC' AND `date` > '2019-01-01 15:06:23'
(0, '')
unable to rollback
I want to know what this "unable to rollback" means and how to solve this multi-condition selection in PyMySQL.
unable to rollback
It means your query has not been successfully executed.
An unclosed connection is usually the cause for that error. You might not have closed the previous connection. You can usually do so with the close method associated with the connection instance.
I tried all possible means. I included backQuotes for the string as suggested some in stack but nothing worked. It repeats the error as usual.
I also tried some queries that worked in other python files still it shows the same. I also tried queries with string without hyphens even it didn't work. I cant find out whats the problem here.
import MySQLdb
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "Studisplay.ui" # Enter file here.
Ui_MainWindow1, QtBaseClass = uic.loadUiType(qtCreatorFile)
class stuDisplay(QtGui.QMainWindow, Ui_MainWindow1,QtGui.QTableWidget):
def __init__(self,ID):
#super(stuDisplay, self).__init__(parent)
QtGui.QMainWindow.__init__(self)
Ui_MainWindow1.__init__(self)
QtGui.QWidget.__init__(self)
self.setupUi(self)
obj = MySQLdb.connect("localhost", "root", "1234567", "python")
#The value of ID here is 14-VEC-244 I also tried `14-VEC-244` but did not work
sql = 'SELECT MEMname FROM Borrowed WHERE MemberID ='+ str(ID)
cursor = obj.cursor()
cursor.execute(sql)
name=cursor.fetchone()
print name
I get this error:
Traceback (most recent call last): File
"/home/gautham/PycharmProjects/LIBALERT/Login.py", line 105, in
pushButton_clicked
self.call = StuSecond.stuDisplay(StuID) File "/home/gautham/PycharmProjects/LIBALERT/StuSecond.py", line 22, in
init
cursor.execute(sql) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in
execute
self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in
defaulterrorhandler
raise errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'VEC' in 'where clause'")
You're passing a string into your WHERE clause, so it must be quoted within the query string that gets passed to the database, something like so:
sql = "SELECT MEMname FROM Borrowed WHERE MemberID = '" + str(ID) + "'"
so that the finished string looks like
sql = "SELECT MEMname FROM Borrowed WHERE MemberID = '14-VEC-244'"
(Note that the single quotes are "forward" quotes, not backticks.)
This would also be an excellent application for a prepared statement; unfortunately I am not familiar with pyqt and so cannot advise you there.
I'm trying to run a function (f) every x seconds (in my case 60) which will close an active database connection if one exists and upon completion opens it again.
I am using threading.timer although I'm having trouble passing the connection into the function, and in some situations the function runs repeatedly with nothing else running.
The function needs to return the connection to globals after it completes and I'm finding it hard to pass the connection to the function and assign the return globally from within the function which is how I believe the threading.timer works:
enter code from socketIO_client import SocketIO
import logging
import json
import MySQLdb as mdb
import os
import threading
con = mdb.connect('localhost','username','password','databaseName')
cur = con.cursor()
def f(con):
if 'con' in globals():
con.close()
print ("Connection closed")
os.system('php -f /home/ubuntu/grab.php')
con = mdb.connect('localhost','username','password','databaseName')
cur = con.cursor()
print ("DB Connection opened")
con = mdb.connect('localhost','username','password','databaseName')
cur = con.cursor()
threading.Timer(60,f,con).start(); ######PROBLEM LINE
return con
def on_connect():
print "Connecting to database"
areas = ['EH','BE']
socketIO.emit('subscribe_areas', areas)
def on_message(answer):
print("\nNew message received")
array = (json.loads(answer))
print (array)
runningIdentity = array["value"]
berthID = array["to"]
area = array["area"]
if berthID:
query = ("SELECT crs FROM signalBerth WHERE signalBerth=\'%s\';"%(berthID))
cur.execute(("%s")%(query))
reply = cur.fetchall()
for row in reply:
crs= row[0]
query = "UPDATE service SET lastSeen = \'%s\' WHERE runningIdentity=\'%s"%(crs,runningIdentity)+"\';" #berthID == crs, need to alter
print (("%s")%(query))
cur.execute(("%s")%(query))
con.commit()
print("affected rows = {}".format(cur.rowcount))
socketIO = SocketIO('http://www.realtimetrains.co.uk', 41280) #opens connection
socketIO.on('connect', on_connect) #sends subscription
socketIO.on('message', on_message) #reads data, creates mysql and executes it
con = f(con) ######FIRST CALL TO FUNCTION
socketIO.wait() #Keeps connection openhere
Error:
Traceback (most recent call last): File "input.py", line 49, in
socketIO.wait() #Keeps connection open File "build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 175,
in wait File
"build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 194,
in _process_events File
"build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 202,
in _process_packet File
"build/bdist.linux-x86_64/egg/socketIO_client/init.py", line 327,
in _on_event File "input.py", line 36, in on_message
cur.execute(("%s")%(query)) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 155, in
execute
charset = db.character_set_name()
_mysql_exceptions.InterfaceError: (0, '') Exception in thread Thread-1: Traceback (most recent call last): File
"/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run() File "/usr/lib/python2.7/threading.py", line 1082, in run
self.function(*self.args, **self.kwargs) TypeError: f() argument after * must be a sequence, not Connection
Perhaps there is a more suited method to my needs, however the important bit it that the connection is closed, the function run and the connection opened again every minute or so. Thought about a cron job, but I'd rather keep my code doing everything.
According to Timer object, its third parameter is args. It is a list, but you pass only the con instead.
You need to replace your problem line with:
threading.Timer(60, f, (con,)).start()