SQL syntax error with python - python

I have a problem that I couldn't solve
I want to update data in a MysQl table but i get this error:
cursor.execute("UPDATE employees SET PhPath='~/Desktop/test/server/dataSet/%s' WHERE id=%s; ",(generate_names(UserID,1),UserID))
File "/home/chiheb/.virtualenvs/cv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/chiheb/.virtualenvs/cv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
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 'User.2.1.jpg'' WHERE id=2' at line 1")
and this is a part of my code:
data = recv_msg(conn)
data = json.loads(data)
UserName = input("enter user's name: ")
UserLastName = input("enter user's last name: ")
UserPost = input("enter user's post: ")
cursor.execute("INSERT INTO employees VALUES (NULL, %s, %s, %s, %s, NULL);",(UserName, UserLastName, UserPost, data['RasID']))
db.commit()
cursor.execute("SELECT LAST_INSERT_ID(); ")
UserIDL = cursor.fetchone()
UserID = UserIDL[0]
JL= data['Jliste']
for i in range(0,10) :
cel = json.loads(JL[i])
file_name = generate_names(UserID,i+1)
img = base64.b64decode(cel['img'])
with open(file_name,'wb') as _file:
_file.write(img)
print "image {} Received ".format(i+1)
cursor.execute("UPDATE employees SET PhPath='~/Desktop/test/server/dataSet/%s' WHERE id=%s; ",(generate_names(UserID,1),UserID))
response = "images Received "
conn.send(response)
db.commit()

The problem is that you can't do partial replacement with a parameter. Generate the path in code and only use "%s" (without the quotes) as the value.

Related

ProgrammingError: 1064 (42000)

I'm trying to scrape data from an .idx file and import the data into the table I created in SQL.
for row in content:
if len(row)!= 0:
row = row.strip('\n')
if str(row).endswith(".txt"):
columns = row.split("|")
#print(columns)
cik = columns[0]
companyname = columns[1]
formtype = columns[2]
datefield = columns[3]
filenames = columns[4]
query= "INSERT class.firmsreports (cik, companyname, formtype, datefiled, filenames) VALUES ('%(1)s', '%(2)s', '%(3)s', '%(4)s', %(5)s)" %{"1": cik, "2": companyname, "3": formtype, "4": datefiled, "5": filenames};
#print(query)
cursor.execute(query)
database.commit()
This is my code and im getting this error: 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 'txt)' at line 1. Any tips on how to fix it?
Use pre3pared statements with an tuple, and so youz need only once to thefine the query string
Your table firmsreports must have those exacte five columns with he same names cik, companyname, formtype, datefiled, filenames in it.
query= "INSERT class.firmsreports (cik, companyname, formtype, datefiled, filenames) VALUES (%s, %s, %s, %s, %s)" ;
for row in content:
if len(row)!= 0:
row = row.strip('\n')
if str(row).endswith(".txt"):
columns = row.split("|")
#print(query)
cursor.execute(query,(columns[0],columns[1],columns[2],columns[3]columns[4]))
database.commit()

Str-based ValueError when using SQLite3 to import values from a variable to a database table

I'm trying to create a simple login program that saves the recorded username and password from variables into an SQLite3 database. Running the program using hardcoded strings works as expected, but when I try to use variables, a str-based TypeError occurs. I tried using str(variable), but that didn't work and I'm unsure what else could be problem. Any help would be appreciated.
import sqlite3
from sqlite3 import Error
import sys
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred")
def create_new_user(new1, new2):
create_users = ("""INSERT INTO users (username, password)
VALUES (?, ?)
;""", str(new1), str(new2))
execute_query(connection, create_users)
create_users_table = """CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
); """
execute_query(connection, create_users_table)
user = input("Would you like to create an account? ")
if "yes" in user:
new1 = input("\nNew username: ")
new2 = input("New password: ")
create_new_user(new1, new2)
else:
sys.exit(0)
Traceback (most recent call last):
File "/Users/scnewmark/Documents/Database/database.py", line 62, in <module>
create_new_user(new1, new2)
File "/Users/scnewmark/Documents/Database/database.py", line 40, in create_new_user
execute_query(connection, create_users)
File "/Users/scnewmark/Documents/Database/database.py", line 18, in execute_query
cursor.execute(query)
ValueError: operation parameter must be str
The execute method expects a SQL query string as the first argument and a tuple of parameters as the second argument, and yet with your:
create_users = ("""INSERT INTO users (username, password)
VALUES (?, ?)
;""", str(new1), str(new2))
and passing create_users as the query argument to do:
cursor.execute(query)
you are passing a tuple as the first argument to the execute method, resulting in the TypeError.
Instead, you can pass the query string and the parameters separately:
def execute_query(connection, query, credentials):
cursor = connection.cursor()
try:
cursor.execute(query, credentials)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred")
def create_new_user(new1, new2):
query = "INSERT INTO users (username, password) VALUES (?, ?);"
credentials = str(new1), str(new2))
execute_query(connection, query, credentials)

mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'X' in 'where clause'

This is my Script:
import mysql.connector
def loginsystem():
db = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="",
db="dbpython")
cursor = db.cursor()
loop = 'true'
while (loop == 'true'):
username = str(input("Username : "))
password = str(input("Password : "))
if (cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s"%(username,password))):
print("Logged İn")
else:
print("Failure")
db.commit()
loginsystem()
I am installing an online system, but I have encountered a problem with the login system. How to Fix "Unknown column 'x' in where clause" or do you have any other code suggestions?
if (cursor.execute("SELECT * FROM users WHERE (username =? password = ?) VALUES(?,?)"(username,password))):
I tried to do it with this method but didn't
Traceback (most recent call last):
File "C:/Users/artun/PycharmProjects/DENEMELER/Login System.py", line 21, in <module>
loginsystem()
File "C:/Users/artun/PycharmProjects/DENEMELER/Login System.py", line 15, in loginsystem
if (cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s"%(username,password))):
File "C:\Users\artun\PycharmProjects\DENEMELER\venv\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\artun\PycharmProjects\DENEMELER\venv\lib\site-packages\mysql\connector\connection.py", line 553, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\artun\PycharmProjects\DENEMELER\venv\lib\site-packages\mysql\connector\connection.py", line 442, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'oziboran123' in 'where clause'
Process finished with exit code 1
this is the output of the code, but I expected the output of the code to be "Logged In" or "Failure"
Consider parameterization and not string interpolation which involves a two-step process of prepared statement and then execution that binds parameters. Below uses two arguments of execute call: cursor.execute(query, params). Also, user and password are reserved words in MySQL which should be escaped with backticks.
Please note the parameter placeholder, %s, for the mysql.connector API should not be confused with Python's modulo string format symbol (which by the way is the less preferred string formatting method in Python for more preferred str.format).
# PREPARED STATEMENT
sql = """SELECT * FROM `users`
WHERE `username` = %s AND `password` =%s
"""
# EXECUTE WITH PARAMS
cursor.execute(sql, (username, password))
Try this code below:
"""SELECT * FROM `users` WHERE `username` '{}' AND `password` '{}'""".format(username,password))

Python Maria DB Syntax

Does anyone know where I am going wrong here? The syntax for the DB update looks correct to me. Also I am wondering if I need to close connection say to open and close a connection within each function. Lets say for example that each function performs a different type of DB command, one for insert, one for update and one for delete, just as a generic example.
Output:
[root#localhost student_program]# python modify_student.py
Connection successful!!
Enter the id of the student record you wish to modify: 21
Is this student personal information you want to modify - y or n: y
Enter the first name: Jake
Enter the last name: Mc Intyre
Enter the email address: jake#noemail.com
Enter the address: 300 Main Street, New York
Enter the DOB in YYYY-MM-DD: 1960-01-01
Traceback (most recent call last):
File "modify_student.py", line 38, in <module>
modify_student()
File "modify_student.py", line 29, in modify_student
cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])
File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 893, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1103, in _read_query_result
result.read()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1396, in read
first_packet = self.connection._read_packet()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1059, in _read_packet
packet.check_error()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 109, 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 MariaDB server version for the right syntax to use near '(firstname, lastname, email, address, DOB)VALUES ('Jake','Mc Intyre','jake#noema' at line 1")
My code:
import os,pymysql
db_root = '/var/lib/mysql/'
db_to_create = 'students'
db_to_use = 'students'
conn = pymysql.connect(host='localhost', user='root', passwd='dbadmin', cursorclass=pymysql.cursors.DictCursor)
print('Connection successful!!')
def modify_student():
student_id = input("Enter the id of the student record you wish to modify: ")
student_info = input("Is this student personal information you want to modify - y or n: ")
if student_info == 'y':
firstname = input("Enter the first name: ")
lastname = input("Enter the last name: ")
email = input("Enter the email address: ")
address = input("Enter the address: ")
DOB = input("Enter the DOB in YYYY-MM-DD: ")
cur = conn.cursor()
command = "use %s; " %db_to_use
cur.execute(command)
sql = 'UPDATE students_info SET (firstname, lastname, email, address, DOB)VALUES (%s,%s,%s,%s,%s) WHERE ID = (%s);'
cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])
print(cur.execute)
conn.commit()
cur.close()
conn.close()
else:
print("else")
modify_student()
The syntax for update is:
UPDATE tablename SET name='%s', email='%s' WHERE id='%s'
You are trying to UPDATE like an INSERT. But UPDATE only supports setting each column name independently, Not with a column list.
Try:
sql = "UPDATE students_info SET firstname='%s', lastname='%s', email='%s', address='%s', DOB='%s' WHERE ID='%s'"
cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])
See https://mariadb.com/kb/en/library/update/
Query statement is nor right. Try this-
sql = 'UPDATE students_info SET firstname="'+firstname+'", lastname=="'+lastname+'", email="'+email+'", address="'+address+'", DOB="'+address+'") Where id="'+student_id+'"'
Hope this helps.

python cannot insert string in table

I did a coding for dynamic updating table. it gave me output,but i can only insert Integers not strings it gives me "operational error" if i enter strings,I tried altering the table field datatype, but still it accepts integers only,I think it needs a change within the program.Please help:
Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
db.commit()
db.close()
what should i change so that it accepts both integers and strings as input?please help
error :
Enter film: 123
Enter title: adarsh
Enter year: 1234
Enter director: 132
**error**
Traceback (most recent call last):
File "C:\Python27\maybe1.py", line 22, in <module>
cursor.execute(query)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'adarsh' in 'field list'")
Datatypes:
file123 int(11),title_ varchar(50),year int(11),director varchar(12)
i think you need to add '%s' for the string and %s to the integers
query = "INSERT INTO films (file123, title_, year, director) VALUES ('%s', '%s', %s, '%s')" % (a.file123, a.title_, a.year, a.director)
or
query = "INSERT INTO films (file123, title_, year, director) VALUES (?,?,?,?)"
curs.excute(query,[a.file123, a.title_, a.year, a.director])
Explanation what wrong with your code:
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
raw_input("Enter film: ") always a string . so you need to convert each variable to appropriate type eg :file123 to int; year to int
now
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
print query
it gives
INSERT INTO films (file123, title_, year, director) VALUES (123, adars, 200, sundar)
but right format should be
INSERT INTO films (file123, title_, year, director) VALUES (123, 'adars', 200, 'sundar')
this happens due to %s directly put values as string without quotes so instead of %s use ?
I think this is better:
cursor.execute("INSERT INTO films (file123, title_, year, director) "
"VALUES (%s, %s, %s, %s)",
(a.file123, a.title_, a.year, a.director))
Just let MySQLdb do the variables formatting job for you, you do not need to add quotes yourself and it's more safe.
Here are examples.

Categories