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()
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
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.
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 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.