MYSQL Incorrect DOUBLE value Python 3 - mysql

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))

Related

Incorrect number of parameters in prepared statement

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()

Im getting an Internal Server error for my Flask app hosted at PythonAnywhere

So when i first deployed my app, it worked really well. It showed all pages, i was able to write and read from my PythonAnywhere MySQL database. Then after 10 minutes I get the internl server error. Then when I reload the app, it works for 10 minutes then goes back to the internal server error. The details below show my code that communicates to my Database, the server.log error code and the error.log code i get as well.
Server Log:
2019-04-29 01:06:40 Mon Apr 29 01:06:40 2019 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request / (ip 10.0.0.162) !!!
==============================================================================
Error Log:
2019-04-29 01:06:40,959: Exception on / [GET]
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/chronic007/TheCronica/index.py", line 21, in home_page
cursor.execute(query)
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 393, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 586, in cmd_query
statement))
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 386, in _send_cmd
packet_number)
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/network.py", line 104, in send_plain
raise errors.OperationalError(str(err))
OperationalError: [Errno 32] Broken pipe
=============================================================================
Here is my python flask file:
from flask import Flask
from flask import render_template
from flask import request
import mysql.connector
app = Flask(__name__)
db = mysql.connector.connect(
host="xxxx.mysql.pythonanywhere-services.com",
user="xxxxx",
passwd="xxxxxx",
database= "xxxxxx"
)
cursor = db.cursor()
#app.route('/')
def home_page():
query = "SELECT * FROM Articles"
cursor.execute(query)
data = cursor.fetchall()
return render_template('index.html', value=data)
#app.route('/static/index.html')
def static_home():
query = "SELECT * FROM Articles"
cursor.execute(query)
data = cursor.fetchall()
return render_template('index.html', value=data)
#app.route('/static/about.html')
def static_about():
return render_template('about.html')
#app.route('/admin')
def admin_page():
return render_template('admin.html')
#app.route('/admin', methods=['POST'])
def submit_form():
query = "INSERT INTO Articles (Title, Author, Date, Description, Content, Link) VALUES (%s, %s, %s, %s, %s, %s)"
if request.method == 'POST' :
title = request.form.get('Title')
author = request.form.get('Author')
date = request.form.get('Date')
description = request.form.get('Description')
content = request.form.get('Content')
link = request.form.get('Link')
val = (title, author, date, description, content, link)
cursor.execute(query, val)
db.commit()
return render_template('admin.html')
You're opening a DB connection at module level (outside your view functions) so it may no longer be valid by the time a view is called; database connections shut down when they're unused for a while, which would explain the issue you're seeing. You should either create the db and cursor objects inside every view function that uses them, or even better use a database connection manager like SQLAlchemy.
This PythonAnywhere help page has more information about connection management, and this blog post has a walkthough for creating a database-backed website using Flask and SQLAlchemy on PythonAnywhere.
First this code is outside of the if statement
val = (title, author, date, description, content, link)
cursor.execute(query, val)
db.commit()
You don't need two views to handle admin just do this
#app.route('/admin', methods=['GET', 'POST'])
def submit_form():
query = "INSERT INTO Articles (Title, Author, Date, Description, Content, Link) VALUES (%s, %s, %s, %s, %s, %s)"
if request.method == 'POST' :
title = request.form.get('Title')
author = request.form.get('Author')
date = request.form.get('Date')
description = request.form.get('Description')
content = request.form.get('Content')
link = request.form.get('Link')
val = (title, author, date, description, content, link)
cursor.execute(query, val)
db.commit()
return render_template('admin.html', message="success")
else:
return render_template('admin.html')

Unknown Column exception in Mysql 1054

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.

Having issues with using mysql SELECT in a function

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)

MySQL python connector IndexError: bytearray index out of range

I'm inserting some data to a database and most of the queries are inserted correctly but I keep getting at least one random query error.
I'm using Python 3, MySQL 5.6.17 and MySQL python connector 2.1.3 (upgraded after having the same problem with 2.0.2).
The queries are run in a Multiprocessing Pool map_async().
multiprocessing.pool.RemoteTraceback: bytearray index out of range
Traceback (most recent call last):
File "./../../../my-python-script.py", line 930, in insert_into_database
mysql_query(mysql_script, values) # <-- My mysql wrapper function
File "./../../../my-python-script.py", line 297, in mysql_query
for row in results:
File "./../../../mysql/connector/cursor.py", line 450, in _execute_iter
result = next(query_iter)
File "./../../../mysql/connector/connection.py", line 520, in cmd_query_iter
yield self._handle_result(self._send_cmd(ServerCmd.QUERY, statements))
File "./../../../mysql/connector/connection.py", line 405, in _handle_result
self._socket.recv(), self.python_charset)
File "./../../../mysql/connector/protocol.py", line 238, in parse_column
(packet, _) = utils.read_lc_string(packet[4:]) # catalog
File "./../../../mysql/connector/utils.py", line 199, in read_lc_string
if buf[0] == 251: # \xfb
IndexError: bytearray index out of range
The above exception was the direct cause of the following exception:
IndexError: bytearray index out of range
Or sometimes I get (from the "for row in results" line)
File "./../../../mysql/connector/cursor.py", line 450, in _execute_iter
result = next(query_iter)
File "./../../../mysql/connector/connection.py", line 520, in cmd_query_iter
yield self._handle_result(self._send_cmd(ServerCmd.QUERY, statements))
File "./../../../mysql/connector/connection.py", line 384, in _handle_result
elif packet[4] == 0:
IndexError: bytearray index out of range
The above exception was the direct cause of the following exception:
IndexError: bytearray index out of range
My setup is something like
class InsertData:
def __init__(self):
with(multiprocessing.Pool(2) as Pool:
Pool.map_async(self.insert_into_database(),set(1,2,3.....))
Pool.close()
Pool.join()
def insert_into_database(self,values):
# use the values to do some calculations then insert to database
mysql_query(mysql_script, values)
def mysql_query(script, values):
cursor.execute(query, values, multi = True)
And the sql script
'INSERT INTO table1 ( column1 ) VALUES ( "x" ); '
'SET #table1 = LAST_INSERT_ID(); '
'INSERT INTO table2 ( column1, column2 ) VALUES ( "y", #table1 ); '
'SET #table2 = LAST_INSERT_ID(); '
...
I'm currently looking at the connector.py and the utils code trying to figure what's happening. But this is too advanced for me.
https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/connection.py#L368
https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/utils.py#L167
In a desperate attempt I've tried setting the buffered to True https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorbuffered.html
I need to read up on bytearrays but I suspect that my query script is causing the problem because I didn't have (I think?) this problem when I ran the queries one connector at a time cursor.execute(query, values, multi = False)
When I send the database connection as described in Accessing a MySQL connection pool from Python multiprocessing the problem disappears.
Something like
mysql_conn = None
def db_conn():
global mysql_conn
mysql_conn = connector.connect(...)
class InsertData:
def __init__(self):
with(multiprocessing.Pool(2, initializer = db_conn) as Pool:
Pool.map_async(self.insert_into_database(),set(1,2,3.....))
Pool.close()
Pool.join()
def insert_into_database(self,values):
# use the values to do some calculations then insert to database
self.mysql_query(mysql_script, values)
def mysql_query(script, values):
cursor = mysql_conn.cursor()
cursor.execute(query, values, multi = True)