Python/MySQL - Error 1064, can't figure it out - python

I've been trying to find out what causes the error. I believe it is in the last query to the database. I've marked it with comments.
This error has been giving me a headache for the past 30 minutes.
import MySQLdb
import time
# Create a database connection
db = MySQLdb.connect(host="******", user="******", passwd="*****", db="*****")
cur = db.cursor()
# Create a query to select all IDs
cur.execute("SELECT id FROM users")
clientArray = []
# Loop over all IDs returned from query,
# save all IDs in the clientArray
for row in cur.fetchall():
clientID = str(row[0])
clientArray.append(clientID)
clientIDInput = ""
while True:
# Check and wait for input
clientIDInput = raw_input("")
if clientIDInput in clientArray:
# Check to see whether user is already signed in to the device
cur.execute("SELECT fitnessStatus FROM users WHERE id=%s", (clientIDInput))
data = cur.fetchone()
if data[0] == False:
cur.execute("UPDATE users SET fitnessStatus='1' WHERE id=%s", (clientIDInput))
checkInTime = time.strftime('%Y-%m-%d %H:%M:%S')
checkOutID = raw_input("")
if checkOutID == clientIDInput:
cur.execute("UPDATE users SET fitnessStatus='0' WHERE id=%s", (clientIDInput))
checkOutTime = time.strftime('%Y-%m-%d %H:%M:%S')
print checkInTime
print checkOutTime
### I BELIEVE THIS IS THE CAUSE OF THE ERROR ###
cur.execute("INSERT INTO activities (id, machinename, checkin, checkout, clientid) VALUES (NULL, Cross Trainer #5, %s, %s, %s)", (checkInTime, checkOutTime, clientIDInput))
# Send checkInTime and checkOutTime to database

There is a syntax error in your INSERT statement. Try to enclose the string 'Cross Trainer #5' in single quotes:
cur.execute("INSERT INTO activities (id, machinename, checkin, checkout, clientid) VALUES (NULL, 'Cross Trainer #5', %s, %s, %s)", (checkInTime, checkOutTime, clientIDInput))`
Luckily, the statement itself is already enclosed in double quotes " so that no further change would be required :)
The error 1064 is a bit misleading. It indicates, amongst others, abuse of a reserved word. And indeed: CROSS is a reserved word.

Related

Mysql table name getting unwanted quotes resulting table does not exist error

import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")
I have the code above and giving me the below error:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist
aud-cad_30mins table does exist and an insert query like below doing its job:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )"""
So when I try to use variables in the query, it gives the error. Why the table name getting unwanted quotes? Checked several tutorials but couldn't find a solution, any ideas?
The table name should be hardcoded in the query string instead of having it there as a placeholder %s, which is meant for the values to be inserted. So if you have the table name in the variable, you can replace it via format() before calling cursor.execute()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)
see the examples in the docs
edit: as Bill mentioned in the comment, dont add the backticks around the %s placeholders.

Inserting a list into MySQL table, id wise

I am trying to insert a list into 1 single column in a row .How do I make the list go in a column in the same row with the same ID? I cannot get the syntax right.
social_media is a list like this
['https://twitter.com/eddylazzarin?ref=cypherhunter', 'https://www.linkedin.com/in/eddy-lazzarin-66059749?ref=cypherhunter', 'https://a16z.com/author/eddy-lazzarin/?ref=cypherhunter']
This is my code
sql = cursor.execute(f"SELECT inv_id FROM Investors WHERE name =\'{name}\'")
pid = cursor.fetchone()
pidf = str(pid)[1:2]
pidff = int(pidf)
try:
cursor.execute("INSERT INTO team_members(inv_id,mem_name,picture,experience) VALUES(%s, %s, %s, %s)", (pidff, port_name, headshot, work_ex,))
list_str = '|'.join(str(item) for item in so_links)
cursor.execute(f"UPDATE team_members WHERE mem_name=\'{port_name}\' SET social_media ('{list_str}')")
raise e
inv_id is the FOREIGN_KEY.
However I cannot get the right syntax
Error:
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 'WHERE mem_name='Eddy Lazzarin' SET social_media
('https://twitter.com/eddylazzar' at line 1
You have missing = in SET & wrong position of it
cursor.execute("UPDATE team_members SET social_media = %s WHERE mem_name=%s",(list_str,port_name))
see the docs

Failed to insert user input into MySQL database

I have created a database and inserted some value using python manual code but when i tried to taking input from user then inserting that input to my database table,i failed as i tried many ways.
Here is my code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Adee11ruchi#",
database="hdatabase"
)
mycursor = mydb.cursor()
name= str(input("What is your first name? "))
address=str(input("enter address:"))
#mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute = ("""INSERT INTO customers (name, address) VALUES (r{}, r{})""".format(name, address))
#val = ('Peter', 'Lowstreet 4')
mydb.commit()
print(mycursor.rowcount, "record inserted.")
It showing me as
What is your first name? diyu
enter address:hiouy
-1 record inserted.
What is the issue,i failed to find out.
You should be using a prepared statement here. Consider this version:
mycursor = mydb.cursor(prepared=True)
name = input("What is your first name? ")
address = input("enter address:")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
mycursor.execute = (sql, (name, address,))
mydb.commit()
The main takeaways points here are that you leave the values to be bound as parameters %s, and then you bind the values as a tuple in the call to cursor#execute. Note that the prepared statement API will handle the proper formatting of the inputs for you.

MySQL Insert / update from python, data from excel spreadsheet

Upsert to MySQL using python and data from excel.
Im working on populating a MySQL DB, using python.
The data is stored on excel sheets.
Because the DB is suppossed to be used for monitoring "projects", there's a posibility for repeated pk, so in that case it need to be updated instead of insert, because a project can have many stages.
Also, there's a value to be inserted in the DB table, that can't be added from the spreadsheet. So i'm wondering if in that case, the insert of this value, most be done using a separated query for it or if theres a way to insert it in the same query. The value is the supplier ID and needs to be inserted between id_ops and cif_store.
And to finish, I need to perform an inner join, to import the store_id using the store_cif, from another table called store. I know how do it, but im wondering if it also must be executed from a sepparated query or can be performed at the sameone.
So far, i have done this.
import xlrd
import MySQLdb
def insert():
book = xlrd.open_workbook(r"C:\Users\DevEnviroment\Desktop\OPERACIONES.xlsx")
sheet = book.sheet_by_name("Sheet1")
database = MySQLdb.connect (host="localhost", user = "pytest", passwd = "password", db = "opstest1")
cursor = database.cursor()
query = """INSERT INTO operation (id_ops, cif_store, date, client,
time_resp, id_area_service) VALUES (%s, %s, %s, %s, %s, %s)"""
for r in range(1, sheet.nrows):
id_ops = sheet.cell(r,0).value
cif_store = sheet.cell(r,1).value
date = sheet.cell(r,2).value
client = sheet.cell(r,3).value
time_resp = sheet.cell(r,4).value
id_area_service = sheet.cell(r,5).value
values = (id_ops, cif_store, date, client, time_resp, id_area_service)
cursor.execute(query, values)
# Close the cursor
cursor.close()
# Commit the transaction
database.commit()
# Close the database connection
database.close()
# Print results
print ("")
print ("")
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print ("Imported", columns,"columns and", rows, "rows. All Done!")
insert()
What you are looking for is INSERT ... ON DUPLICATE KEY UPDATE ...
Take a look here https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
Regarding the extraneous data, if its a static value for all rows you can just hard code it right into the INSERT query. If it's dynamic you'll have to write some additional logic.
For example:
query = """INSERT INTO operation (id_ops, hard_coded_value, cif_store, date, client,
time_resp, id_area_service) VALUES (%s, "my hard coded value", %s, %s, %s, %s, %s)"""

How to store data into database using PyMYSQL in python

I am scraping a website and getting the companies details from it, Now I trying to store the data into database. But I am getting some error like
raise InternalError(errno, errorvalue)
pymysql.err.InternalError: (1054, "Unknown column 'companyaddress' in 'field list'")
Here is my code
for d in companydetail:
lis = d.find_all('li')
companyname = lis[0].get_text().strip()
companyaddress = lis[1].get_text().strip()
companycity = lis[2].get_text().strip()
try:
companypostalcode = lis[3].get_text().strip()
companypostalcode = companypostalcode.replace(",","")
except:
companypostalcode = lis[3].get_text().strip()
try:
companywebsite = lis[4].get_text().strip()
except IndexError:
companywebsite = 'null'
print (companyname)
print (companyaddress)
print (companycity)
print (companypostalcode)
print (companywebsite)
try:
with connection.cursor() as cursor:
print ('saving to db')
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
connection.commit()
connection.close()
I am getting my data which I want but it I am not able to store data into database.
The result which I get while print (companyname) and print (campanyaddress) is :
NINGBO BOIGLE DIGITAL TECHNOLOGY CO.,LTD.
TIANYUAN INDUSTRIAL ZONE CIXI NINGBO
ZHEJIANGNINGBO
315325
http://www.boigle.com.cn
You cannot simply use variable names inside a query string as you do:
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
Instead, pass your variables into the query making it parameterized:
params = (companyname, companyaddress, companycity, companypostalcode, companywebsite)
cursor.execute("""
INSERT INTO
company
(companyname, address, city, pincode, website)
VALUES
(%s, %s, %s, %s, %s)
""", params)
In
cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
the values in the second bracket are interpreted as table fields, rather than as python variables. Try
cursor.execute("""INSERT INTO company(
companyname,address,city,pincode,website)
VALUES (%s, %s, %s, %s, %s)""",
(companyname, companyaddress, companycity,
companypostalcode, companywebsite))
instead. You may also want to consult the docs on that.

Categories

Resources