Python SQL Update Syntax Issues - python

Hello I was following Python MYSQL update statement and managed to produce this code for my programme's SQL Update with variables function:
def editInfo(start, userName):
newFavGenre = input("Enter your favourite genre")
newFavArtist = input("Enter your favourite artist")
## userName is a global variable
con = lite.connect(db)
cur = con.cursor()
cur.execute ("""
UPDATE users
SET favGenre=%s, favArtist=%s
WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
results = cur.fetchall()
return result
mainmenu()
And keep expericiencing this error code:
sqlite3.OperationalError: near "%": syntax error
Any ideas where I am going wrong?

It appears the post you are looking at is for MySQL and I conjecture that you're using the sqlite3 python interface based on your error.
Looking at the sqlite3 docs...
cur.execute("""
UPDATE users
SET favGenre=%s, favArtist=%s
WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
Should instead be
cur.execute("""
UPDATE users
SET favGenre=?, favArtist=?
WHERE username=?
""", (newFavGenre, newFavArtist, userName))
You could also use their named style which instead of taking a tuple takes a dictionary.
cur.execute("""
UPDATE users
SET favGenre=:genre, favArtist=:artist
WHERE username=:username
""", {'genre':newFavGenre, 'artist': newFavArtist, 'username':userName})

Related

Variable Input not inserting into SQLite3

i'm a bit of an amateur IT Professional who has been getting to grips with Python and Django. This query is just for Python and SQLite3.
So I have the following code, which is meant to take an input from the user, and then pass it to a function I have created.
from dbadd import inputdetails
import sqlite3
conn = sqlite3.connect('torndata.db')
c = conn.cursor()
print('Enter Name')
u_name = str(input())
print('Enter Age')
u_age = int(input())
print('Enter Gender')
u_gender = str(input())
inputdetails(u_name, u_age, u_gender)
conn.close()
And this is the function it is calling:
import sqlite3
conn = sqlite3 . connect ( 'torndata.db' )
cursor = conn.cursor ()
def inputdetails(u_name,u_age,u_gender):
cursor.execute("""
INSERT INTO userdata(name, age, gender)
VALUES (?,?,?)
""", (u_name, u_age, u_gender))
conn.commit()
I get no errors when it runs, but when I run the following, it shows no data has been moved to the table I have specified.
c.execute("SELECT * FROM userdata")
print(c.fetchall())
conn.commit()
conn.close()
The database is already created within SQLite3 and the table has been set up, I can query it directly.
Bad indent. The commit statement is not part of the function.

Python variables in MySQL execute command

I've looked for an answer everywhere and didn't manage to find any suitable one.
This is my code:
conn = pymysql.Connect(host="host", user="user", passwd="password", db="database")
dbhandler = conn.cursor()
table_name = today_date.split(" ")[0]
execute_it = """CREATE TABLE %s (
USERNAME CHAR(20) NOT NULL,
X CHAR(10),
Y INT,
Z INT,
A INT)"""
try:
dbhandler.execute(execute_it, table_name)
except:
print("\n----------------------------\nFailed to create table.")
Now I've tried to do it like this.
I tried with % separating in execute.
I tried with ? instead of %s.
I tried it with many more options and yet none of them worked for me and I failed to create the table
This is the exception I get:
(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 ''11/14/18' (\n USERNAME CHAR(20) NOT NULL, \n
X CHAR(10' at line 1")
Using 5.5.52-MariaDB.
Thank you!
EDIT:
Managed to get through it.
Thanks Pavel Francírek for the help.
Problem is not in placeholder, but in date format. Character "/" is not allowed in table name. Try something like:
table_name = today_date.split(" ")[0].replace("/","")
I assume that all numbers in your date format are 2-digit.

PyMySQL assigning a variable to table name, in Python

I am using PyMySQL in Python 2.7. I have to create a function - where, given a table name, the query will find unique values of all the column names.
Since there are more than one tables involved, I do not want to hard-code table name. Now, a simpler query is like:
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM `Table_1` ORDER BY `Trend` DESC ")
I want to do something like:
tab = 'Table_1'
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM tab ORDER BY `Trend` DESC ")
I am getting the following error:
ProgrammingError: (1146, u"Table 'Table_1.tab' doesn't exist")
Can someone please help. TIA
Make sure the database you're using is correct,and use %s to format you sql statement.
DB_SCHEMA='test_db'
table_name='table1'
connection = pymysql.connect(host=DB_SERVER_IP,
port=3306,
db=DB_SCHEMA,
charset='UTF8',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
sql = "SELECT DISTINCT(`Trend`) AS `Trend` FROM `%s` ORDER BY `Trend` DESC"%(table_name)
cursor.execute(sql)
connection.commit()
except Exception as e:
print e
finally:
connection.close()
Hope this helps.

Exporting data from Entry widgets into SQL code

So I found this really useful piece of code earlier that created entry boxes and when they were created I could edit what was inside of them. The data that was loaded in was taken from an SQL table. Once I have made edits to the entry boxes, I want to submit the data to overwrite the data that had previously been in that sql record, as it it was being edited. The code I found was this:
for item in selectedetails:
entry = Entry(top2)
entry.insert(0, item)
entry.pack()
entries.append(entry)
I want it to be able to enter an sql code. I have tried this but it doesn't work. I think I am doing it wrong.
def submitedit():
for entry in entries:
print(entry.get())
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
("?"," ?"," ?").format(entry.get()))
cursor.close()
db.commit()
db.close()
I have also tried this:
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
(entry.get())
cursor.close()
db.commit()
db.close()
Thanks.
with sqlite3.connect('TestFile') as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "UPDATE Table Name=?, Desc=? WHERE ID=?"
cursor.execute(sql,(Name,Descr))
db.commit()
Note that the order that you put your values in cursor.execute line must match up to the order used in sql variable, otherwise the wrong values will be used at the wrong time. Also i have taken out set ID due to that being what you are searching off which im guessing is your primary key, in databases you should not edit the primary key. The primary key should be auto incremented as well.

Python & PostgreSQL: Function to insert variable arg into table?

I am trying to do the code as follows to register a player with a given name, but I can't get the argument name to do anything… I thought that %s was the variable to insert a string into a database, but it doesn't seem to work.
import psycopg2
def registerPlayer(name):
"""Registers new player."""
db = psycopg2.connect("dbname=tournament")
c = db.cursor()
c.execute("insert into Players values (%s);")
db.commit()
db.close()
registerPlayer("Butter")
When I run it, I get the error message:
ProgrammingError: syntax error at or near "%"
LINE 1: insert into Players values (%s);
You haven't actually passed the parameter into the execute method.
c.execute("insert into Players values (%s);", (name,))

Categories