Python/Flask:
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (email TEXT NOT NULL UNIQUE, password TEXT)')
print('Table created')
Then in another method
def create_user(email, hashedpw):
try:
cur.execute('INSERT INTO users VALUES (?, ?)', (email, hashedpw))
conn.commit()
return "works"
except:
print(str(sqlite3.Error))
return None
Even if I input the same email 10 times it still records the data in the database and doesn't give an error. I clearly set it to UNIQUE then why isnt it working?
Your syntax looks good so only explanation that comes to mind is:
You already have a table named users in your database which doesn't have the UNIQUE constraint and since you are using IF NOT EXISTS, that table remains as it is.
Related
I have one page HTML with few submit buttons with different names and values. I have all the names of the buttons in one db in SQL. When the user enter in the page usually he click just in one button each time and the form is submitted. How can I loop through this buttons in my flask/python program?
connection = sqlite3.connect('world.db')
cursor = connection.cursor()
sqlite_select_query = """SELECT name FROM countries"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
for row in records:
wish = request.form[row[0]]
try:
db.execute("INSERT INTO userinput (user_id, wish, country_name) VALUES (?, ?, ?)", user_id, wish, row[0])
except ValueError:
db.execute("UPDATE userinput SET wish = ? WHERE user_id =? AND country_name=?", wish, user_id, row[0] )
except:
pass
I have one error 400 Bad request.
Ps.: I already tried to put the value of row between ' and ". Doesn't changed anything.
If I put my request.form inside the try session, it just pass.
I put before few "prints" to see where is the error and see that is in the request form.
If I put the name direct in request form and outside the loop for example ‘’’ request.form[“Brazil”]’’’ I can insert in the database with no problems.
Thanks.
I am pretty sure request.form does not contain all countries, just the one associatted button is clicked. You could look at server logs, probably you see info about missing key in request.form. So what you want to is find that specific one:
wish = request.form.get(row[0])
if wish is None:
continue
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 am having a hard time understanding why psycopg2 has a problem with the word 'user'. I am trying to insert values into a table called user with the columns user_id, name, password. I am getting a programmingError: syntax error at or near "user". open_cursor() is a function used to open a cursor for database operations.
Here is my code:
query = """INSERT INTO user (name, password) VALUES (%s, %s);"""
data = ('psycouser', 'sha1$ba316b$52dd71da1e331247f0a7ab869e1b072210add9c1')
with open_cursor() as cursor:
cursor.execute(query, data)
print "Done."
because user is a part of sql language.
try taking it in dbl quotes:
query = 'INSERT INTO "user" (name, password) VALUES (%s, %s);'
I am creating a simple app in pyramid . While inserting data i am getting db locked error.
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked [SQL: 'INSERT INTO users (name, email, number) VALUES (?, ?, ?)'] [parameters: ('test', 't#t.com', '123654')]
But first time it inserts the data correctly and on 2nd time it gives this error.
Any idea why this is happening second time ?
Here is my code :
name = request.params['name']
email = request.params['email']
no = request.params['number']
DBSession.add(User(name, email, no))
# Get the new ID and redirect
users = DBSession.query(User).all()
SQLite can only handle 1 concurrent transaction.
Have you tried commit()before performing a query() then close() to end the session?
name = request.params['name']
email = request.params['email']
no = request.params['number']
DBSession.add(User(name, email, no))
# Commit the transaction if complete
DBSession.commit()
# Get the new ID and redirect
users = DBSession.query(User).all()
# Close the session
DBSession.close()
Hey I'm okay with writing to the table, except unable to check of the data is already there and if the data is then don't write the data and print a value saying that it already exists.
Here is what I have so far
def createAccount():
username = raw_input("username: ")
password = raw_input("password: ")
c.execute("INSERT INTO Logindetails(Username, Password) VALUES (?,?)",
(username, password,))
conn.commit()
Thanks if you can help me, its for my coursework and I'm pretty new to all this.
If you change the create table statement to the following, sqlite will know that each username must be unique because you're defining a 'PRIMARY KEY', one that must be unique:
c.execute("""CREATE TABLE LoginDetails
(Username text PRIMARY KEY, Password text)""")
If you then attempt to insert a row into the table with an existing username, an integrity error will occur:
IntegrityError: column username is not unique
You can catch this (and other errors similarly) using a try, except clause as follows (this assumes you're using sqlite3):
try:
c.execute("INSERT INTO Logindetails(Username, Password) VALUES (?,?)",(username, password,))
except sqlite3.IntegrityError:
print("Username already exists!")