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!
Related
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 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']}"
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,))
I am creating a Flask Application that connects to a locally-hosted MySQL database (Using SQL-Alchemy ORM). When a user creates an account, I have a method is_taken and returns True or False depending on if a user with that username already exists.
Here is the method:
def is_taken(username):
q = session.query(User).filter(User.username == username).first()
return not (q is None)
Although not on a regular basis, the following error occurs at least once a day:
StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect
until invalid transaction is rolled back [SQL: u'SELECT users.uid AS
users_uid, users.username AS users_username, users.fullname AS
users_fullname, users.password AS users_password, users.score AS
users_score, users.totalattempted AS users_totalattempted,
users.totalcorrect AS users_totalcorrect, users.settings AS
users_settings \nFROM users \nWHERE users.username = %s \n LIMIT
%s'] [parameters: [immutabledict({})]]
The error is triggered specifically on:
q = session.query(User).filter(User.username == username).first()
I appreciate the help!
you've had a invalid transaction before executing this query. first of all I suggest you to find the problem of previous query that led to this problem. and for fixing this problem you execute session.rollback() before running the query.