I'm running the following Python3 code on a Sqlite3 database:
db.execute("UPDATE user SET ? = ? WHERE id = ?", (name, quantity, str(g.user['id'])))
where db is my cursor object. However, this produces the error
sqlite3.OperationalError: near "?": syntax error.
Is this the right syntax for cursor.execute()?
f-strings would do the job in python3
db.execute(f"UPDATE user SET {name} = {quantity} WHERE id = {str(g.user['id']}"
Related
query=SQL(
"CREATE USER {id} WITH PASSWORD %s".format(
id=Identifier(id)
)
)
try:
self.cur.execute(
query=query,
vars=[password]
)
except DuplicateObject:
print("{id} User already created.".format(id=id))
else:
print("{id} User create.".format(id=id))
This is the code to create a user in postgresql.
query=SQL(
"CREATE USER {id} WITH PASSWORD %s".format(
id=Identifier(id)
)
)
ID argument is defined as identifier class.
self.cur.execute(
query=query,
vars=[password]
)
The password argument is defined as a variable of the execution function.
psycopg2.errors.SyntaxError: 오류: 구문 오류, "(" 부근
LINE 1: CREATE USER Identifier('administrator') WITH PASSWORD 'Y2zfW...
When I run the code, I get a syntax error.
Why am I getting a syntax error?
You are calling the wrong .format. This works for me:
query = sql.SQL("CREATE USER {} WITH PASSWORD %s").format(sql.Identifier('falken'));
c.execute(query, ['pencils'])
Notice that I am calling .format on the SQL object, not on the string!
I am trying to implement a function in my database manager class that checks if a row (user) exists (through their email) in my MySQL table.
See code below:
def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
mysql_hasuser_query = """
SELECT COUNT(1) FROM {t_name} WHERE email = {u_email}
""".format(t_name=table_name, u_email=user_credentials.email)
cursor = self.connection.cursor()
cursor.execute(mysql_hasuser_query)
if cursor.fetchone()[0]:
print("User exists in database!")
return True
I am receiving the following syntax error 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 '#gmail.com' at line 1
However, I implemented this in MySQL query editor and it worked fine. I am not sure what I am doing wrong here.
You're not quoting the email in the query. But you should use a parameter instead of formatting the string into the query.
def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
mysql_hasuser_query = """
SELECT COUNT(1) FROM {t_name} WHERE email = %s
""".format(t_name=table_name)
cursor = self.connection.cursor()
cursor.execute(mysql_hasuser_query, (user_credentials.email,))
if cursor.fetchone()[0]:
print("User exists in database!")
return True
I'm using Python 3.7.5 and SQLite3 3.X as well as Tkinter (but that's irrelevant) and I can't seem to update my table called "Account"
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
The try bit is just to create the table if there's not already one and if there is it goes on to update the table
I know for a fact there's columns called Application, Username, Password and the variable.get() all returns the proper string
The oid being X[3] gives you an integer
The program runs but it doesn't actually seem to update anything.
Any help with the formatting or just in general would be appreciated
I think that you need just commit your change
I assume that you get cursor from a connectio,
For instance something like that should work:
import sqlite3
conn = sqlite3.connect('example.db')c = conn.cursor()
Cursor = conn.cursor()
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
conn.commit()
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
conn.commit()
conn.close()
Referece
https://docs.python.org/3/library/sqlite3.html
I'm trying do delete a user from my database using python and sqlite.
import sqlite3
database_connection = sqlite3.connect('test.db')
delete_username_input = input("Which user you would like to delete?\n\n")
sql = ("DELETE * from USERS where USERNAME = ?")
args = (delete_username_input)
database_connection.execute(sql, args)
database_connection.commit()
database_connection.close()
When running the code above, I get the following error:
sqlite3.OperationalError: near "*": syntax error
Any idea what might be causing this error?
The table that I use has been created using the following syntax:
conn.execute('''CREATE TABLE USERS
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
USERNAME TEXT NOT NULL,
PASSWORD TEXT NOT NULL,
WINS FLOAT NOT NULL,
LOSES FLOAT NOT NULL,
GAMESPLAYED FLOAT NOT NULL,
WINPERCENT FLOAT NOT NULL );''')
Any help will be appreciated.
Your SQL syntax is wrong. It should be
DELETE from USERS where USERNAME = ?
without the *
Check it out here
I have implemented most other basic database transactions including insert,update,select with similar syntax,but on trying to delete,i get error
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
What would the correct syntax be? I must delete according to user input. Here is a shortened version of my code,minus the insert,select,update part.:
elif (choice == 4):
mail=raw_input('Enter email of user to be deleted:')
print 'Deleting..'
delete_user_details(mail)
def delete_user_details(email):
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql,email)
You need to pass query parameters to cursor.execute() as a tuple, even for a single parameter. Try this:
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql, (email,))