I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.
def atualizaCartelaTabela(campo,valor,jogador):
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
except Error as e:
print("Erro ao atualizar campos da tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
def atualizaCartelaTabela(campo,valor,jogador):
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
except Error as e:
print("Erro ao atualizar campos da tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
atualizaCartelaTabela('Um',2,'Jogador 1')
The error I'm getting:
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 ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2
And, this is the function used to create the table(working):
def criaTabelaCartela():
try:
connection = mysql.connector.connect(host='localhost',
user='root',
password='root',
database='modular')
cursor = connection.cursor()
cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
connection.commit()
except Error as e:
print("Erro ao criar tabela Cartela ->", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
Looking at these 3 statements for what's causing the error:
sql = """UPDATE Cartela
SET %s = %s
WHERE PONTOS = %s"""
atualiza = (campo,valor,jogador)
cursor.execute(sql,atualiza)
When you put SET X = "y" in the update query, the column name X cannot be parameterised. Only the values.
So the column name for campo should be substituted directly in the SQL string, not during execute - but note that this is UNSAFE. Change the first parameter to the {} notation for format and leave the values as %s so that they are parameters for execute():
sql = """UPDATE Cartela
SET {} = %s
WHERE PONTOS = %s""".format(campo) # unsafe
atualiza = valor, jogador
cursor.execute(sql, atualiza)
As a safety check, make sure that the value of campo is the name of one of the columns of the table, except PONTOS or any of the import key columns. Better to check that it's in a white-list of column that you want to allow updating.
I am guessing the int - 2 is the problem here .
Try this out :
Make your SQL-query this :
sql = """
UPDATE Cartela
SET %s = CAST(%s AS int)
WHERE PONTOS = %s
"""
And where you're calling the method atualizaCartelaTabela make it this :
atualizaCartelaTabela('Um','2','Jogador 1')
Related
I would like to know why all seems to be okay but nothing is insert in my mysql database ?
I get some data from an api and I would like to insert data in table.
Using flask, python, pymysql
Thanks in advance
api = Flask(__name__)
def connect():
db = pymysql.connect(database='rtap',port=3306, host='127.0.0.1', user='root', password='',ssl_ca="{ca-cert filename}", ssl_disabled=True)
log.basicConfig(level=log.DEBUG, format='%(asctime)s %(levelname)s:\n%(message)s\n')
print("Connexion réussie")
return db
#api.route('/')
def base():
return jsonify({"version":"1.0"})
#api.route('/azure', methods=['GET'])
def read():
db = connect()
log.info('Reading Datas')
plane = "SELECT * FROM `plane`;"
cursor = db.cursor()
cursor.execute(plane)
output = cursor.fetchall()
return jsonify(output)
#api.route('/azure', methods=['POST'])
def write():
db = connect()
cursor = db.cursor()
req = request.json["response"]
# cursor.executemany("INSERT INTO `plane` (aircraft_icao, reg_number) VALUES (%s, %s);", req)
# print(req)
key = []
for i in req:
try:
if (key==[]) :
plane = "INSERT INTO `plane` (aircraft_icao, reg_number) VALUES ('{}', '{}')".format(i["aircraft_icao"], i["reg_number"])
key.append(i["reg_number"])
else:
if(i["reg_number"] not in key) : #si la key n'a pas encore été utilisée, on peut ecrire la requette, sinon on ne fait rien
plane+= ", ('{}', '{}')".format(i["aircraft_icao"], i["reg_number"])
key.append(i["reg_number"])
except Exception as e:
print("failed")
# print(plane)
cursor.execute(plane)
return jsonify(req)
if __name__=='__main__':
api.run(debug=True, port=5000, host='0.0.0.0')
traceback
Assuming that the INSERT statement looked good at that debugging print function, then you probably need to commit the material to the DB after INSERT. Try adding
db.commit()
cursor.close()
after cursor.execute().
You need to commit your table changes by doing
db.commit()
immediately after each INSERT or sequence of INSERTs. Read this.
I successfully access the database, however, I can't load the table inside the database. I am quite sure that the name of the table is correct, the database is a mimic iii database. Please give me a helping hand, thanks a lot!
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="xxxxxxx",
host="localhost",
port="5432",
database="mimic")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from admissions"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
admissions_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in admissions_records:
print("x = ", row[0], )
print("y = ", row[1])
print("z = ", row[2], "\n")
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Here's the output:
Error while fetching data from PostgreSQL relation "admissions" does not exist
LINE 1: select * from admissions
^
PostgreSQL connection is closed
i'm studying about mysql connection with python(pycharm)
i have question about curs.execute()
when it work and when it not work...
in my code i write remarks about not working point
import pymysql
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성
# curs = conn.cursor()
print("Connected to MySQL")
sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"
# sql = "select* from db_score"
curs.execute(sql)
#this point not work :(
except Exception as e:
print(str(e))
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
and fetchall() didnt work :(\
import pandas as pd
import pymysql
xl_file = 'db_score.xlsx'
df = pd.read_excel(xl_file)
tp = list(df.itertuples(index=False, name=None))
# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
#curs = conn.cursor(pymysql.cursors.DictCursor)
curs = conn.cursor()
print("Connected to MySQL")
sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
for i in range(0, len(df.index)):
# print('hi')
curs.execute(sql, tp[i])
#why work i dont know because other part is not working
# sql2 = "SELECT* from db_score"
# curs.execute(sql2)
# try execute, but not work
records = curs.fetchall()
for row in records:
print("why didn't work")
print(row)
#print not work :(
conn.commit()
except Exception as e:
print(str(e))
conn.rollback()
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
please comment why work and why not work please...
thanks for watching
db connection is so hard:(
I have a piece of code which is taking Windows logs and inserting various pieces of information into an mySQL database. The code is running perfectly with no errors, but does not actually input the data into the table. The table remains blank. I pulled my mySQL syntax from an example with some modification, so I'm not entirely sure what is going wrong. I have a feeling it has either to do with the data types, or some changes I made to the syntax.
import sys
import pymysql
import pymysql.cursors
import win32evtlog # requires pywin32 pre-installed
import win32evtlogutil
import time
server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags =
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
events = win32evtlog.ReadEventLog(hand, flags,0)
while True:
for event in events:
evt_tp = event.EventType
if evt_tp != (1 or 2 or 8):
eve_cat = str(('Event Category:', event.EventCategory))
eve_timegen = str(('Time Generated:', event.TimeGenerated))
eve_srcnm = str(('Source Name:', event.SourceName))
eve_id = str(('Event ID:', event.EventID))
eve_typ = str(('Event Type:', event.EventType))
data = event.StringInserts
if data:
print ('Event Data:')
for msg in data:
print(msg)
print(type(eve_cat))
print(type(eve_timegen))
print(type(eve_srcnm))
print(type(eve_id))
print(type(eve_typ))
print(type(data))
time.sleep(10)
else:
eve_cat = ('Event Category:', event.EventCategory)
eve_timegen = ('Time Generated:', event.TimeGenerated)
eve_srcnm = ('Source Name:', event.SourceName)
eve_id = ('Event ID:', event.EventID)
eve_typ = ('Event Type:', event.EventType)
data = event.StringInserts
print('There were no errors found')
print(eve_cat)
print(eve_timegen)
print(eve_srcnm)
print(eve_id)
print(eve_typ)
print(data)
time.sleep(10)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='ptest',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName',
'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `Type` FROM `win_logs` WHERE `Category`=%s"
cursor.execute(sql, ('webmaster#python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
I can be very wrong.
But this is python.
Indentation matter.
Try just:
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName`, 'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
I guess your cursor is out of with scope
I'm running into some trouble running python/mysqldb on my raspberry pi. This is a pretty simple script, so I'm not sure what I'm missing. The "SELECT * FROM..." runs with no problem, but I can't seem to update the table with new values. The script runs without throwing errors, but when I ctrl-C, it gives me this:
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in bound method DictCursor.__del of MySQLdb.cursors.DictCursor object at 0x19dfd90
Here's my script:
dhost = "localhost"
duser = "root"
dname = "rpi"
dpass = "datPassword"
import MySQLdb
try:
con = MySQLdb.connect(dhost,duser,dpass,dname);
cur = con.cursor(MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
def websiteToSensor():
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
return
while True:
websiteToSensor()
Does anyone have an idea as to why my table isn't updating? Thanks!
***EDIT: SOLUTION***
Thanks to Martijn Pieters, here's my new websiteToSensor() code:
def websiteToSensor():
cur = con.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
num = int(cur.rowcount)
if num > 0:
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
con.commit()
cur.close()
con.commit()
else:
cur.close()
con.commit()
return
Try committing your changes:
def websiteToSensor():
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
con.commit()
return