I have a table "Users" with the column "g_score". The other column I am storing are "username". I am trying to send an update to g_score via the username I get. I send the request and the value does not update. g_score is stored as an INT. I am looking to increment the value by + 1 each time.
The g_score value is default = 0
The value is not being updated by the following code
I'm going to leave some snippets here-
Creating the table -
cursor.execute("CREATE TABLE IF NOT EXISTS Users(username TEXT,hash TEXT,salt TEXT,g_score INT)")
If the user does not exist- we do
cursor.execute("INSERT INTO Users VALUES(?, ?, ?, ?)", (username, hashed_password, salt, 0))
This following code does not update the g_score-
db = lite.connect('log.db', check_same_thread=False)
cursor = db.cursor()
sql = ("UPDATE Users SET g_score = g_score + 1 WHERE username = ?")
cursor.execute(sql, [g_winner.get_name()])
Related
I am running 3 consecutive and dependent SQL queries and I am wondering if my code could be more efficient. I had to create 3 separate cursors to execute my method. What can I do to make it more efficient?
What I am doing in that method is:
Insert a new contributor in my contributors table based on the values send on the form
Get the primary key of that new contribution which is it's contributor_id
Insert a new question on the questions table and the foreign key of that table is the contributor_id from the contributors table
I don't want to use an ORM such as SQLAlchemy.
conn = pymysql.connect(
host = 'localhost',
user = 'root',
passwd = 'xxx!',
db = 'xxx'
)
#app.route('/add_contributor',methods = ['POST', 'GET'])
def add_contributor():
name = request.form.get('contrib_name')
question = request.form.get('question')
sql_1 = "INSERT INTO contributors (name) VALUES (%s)"
sql_2 = "SELECT contributor_id from contributors WHERE name=(%s)"
sql_3 = "INSERT INTO questions (contributor_id, question_text) VALUES (%s, %s)"
cursor = conn.cursor()
cursor.execute(sql_1, name)
cursor.fetchall()
conn.commit()
cursor_2 = conn.cursor()
cursor_2.execute(sql_2, name)
contrib_val = cursor_2.fetchall()
contrib_id = contrib_val[0][0]
cursor_3 = conn.cursor()
cursor_3.execute(sql_3, (contrib_id,question))
cursor_3.fetchall()
conn.commit()
Here is the code I wrote. But when compiling, it says that LIMIT and OFFSET is not defined.
def sql_delete(user_id, task_number):
cur = connection.cursor()
cur.execute('DELETE FROM tasks WHERE user_id = (SELECT user_id FROM tasks WHERE user_id = ? LIMIT 1 OFFSET ?)', (user_id, task_number, ))
connection.commit()
UPDATE
Just now I understood what you did want to manage. Just give a try this:
def sql_delete(user_id, task_number):
cur = connection.cursor()
cur.execute('DELETE FROM tasks WHERE user_id = (SELECT user_id FROM tasks WHERE user_id = ? LIMIT 1 OFFSET ?)', (user_id, int(task_number)))
connection.commit()
I am trying to get the ID of a newly inserted row by using OUTPUT. However, I encountered the HY010 error. The following query/code is what I use:
string = """
SET NOCOUNT ON;
DECLARE #NEWID TABLE(ID INT);
INSERT INTO dbo.t1 (Username, Age)
OUTPUT inserted.id INTO #NEWID(ID)
VALUES(?, ?)
SELECT ID FROM #NEWID
"""
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
the last line id = cursor.fetchone()[0] led to a HY010 error (see below). Any advice would be greatly appreciated!
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
I was able to reproduce your issue, and I was able to avoid it by retrieving the id value immediately after the INSERT and before the commit. That is, instead of
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
I did
cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0] # although cursor.fetchval() would be preferred
cursor.commit()
For me only this worked with Azure SQL Serverless (using pyodbc==4.0.28):
cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT ##IDENTITY AS ID;")
return cursor.fetchone()[0]
If you're using SQLAlchemy with an engine, then you can retrieve the PyODBC cursor like this before running the query and fetching the table ID.
connection = sql_alchemy_engine.raw_connection()
cursor = connection.cursor()
result = cursor.execute(
"""
INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId
VALUES (?, ?);
""",
col1_value,
col2_value,
)
myTableId = cursor.fetchone()[0]
cursor.commit()
print("my ID is:", myTableId)
I have the following function:
def credential_check(username, password):
conn = sqlite3.connect('pythontkinter.db')
c = conn.cursor()
idvalue = c.execute('''SELECT ID FROM userdetails WHERE username = "{0}"'''.format(username)).fetchall()
print(idvalue)
I wish to assign the value of ID in my userdetails table to the variable idvalue in the row where the inputted username = userdetails username, however when I use this fetchall() I get [('0',)] printed out rather than just 0.
How do I go about doing this?
Thanks
You can use fetchone() if you only want one value. However, the result will still be returned as a tuple, just without the list.
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS testing(id TEXT)''')
conn.commit()
c.execute("""INSERT INTO testing (id) VALUES ('0')""")
conn.commit()
c.execute("""SELECT id FROM testing""")
data = c.fetchone()
print data
# --> (u'0',)
You can also use LIMIT if you want to restrict the number of returned values with fetchall().
More importantly, don't format your queries like that. Get used to using the ? placeholder as a habit so that you are not vulnerable to SQL injection.
idvalue = c.execute("""SELECT ID FROM userdetails WHERE username = ?""", (username,)).fetchone()
I'm writing a python-program that is supposed to enter some data into a database. This does not work. Here's the code:
dbcon = lite.connect('spcbase.db') # Connects to database file spcbase.db.
print "Connected to database"
cur=dbcon.cursor() # Creates database cursor.
print "Cursor defined"
cur.execute("CREATE TABLE IF NOT EXISTS spectrum(spectrumID INTEGER PRIMARY KEY AUTOINCREMENT, seriesID INTEGER, scan_ang DECIMAL, Path TEXT)")
cur.execute("CREATE TABLE IF NOT EXISTS series(seriesID INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, gpsx DECIMAL, gpsy DECIMAL, colprec DECIMAL, refangle DECIMAL)")
# Executes SQL-query that will create one table of spectrums
# and one table over series of measurements, should these
# tables or this database not exist.
cur.execute("INSERT INTO series(date, gpsx, gpsy, colprec, refangle) VALUES(CURRENT_DATE, ?, ?, ?, ?)", [AP[0], AP[1], 6, refangle])
dbcon.commit()
cur.execute("SELECT MAX(seriesID) FROM series")
dbcon.commit()
current_series = cur.fetchone()[0]
src = u'.\\MaestroData'
print src
dest = u'.\\target'
print dest
files=getspc(src)
i=0
for mfile in files:
oldpath=os.path.normpath(os.path.join(src,mfile))
print "oldpath: ", oldpath
newpath=os.path.normpath(os.path.join(dest,mfile))
print "newpath", newpath
try:
os.rename(oldpath,newpath)
except:
print "File not moved."
cur.execute("INSERT INTO spectrum(seriesID, scan_ang, Path) VALUES (?, ?, ?)", [current_series, scan_dirs[i], newpath])
dbcon.commit()
i=i+1
(This is not the entire program, only the database handling part.) When this is run a file called spcbase.db is created. It has size 0 and contains nothing. Where does it go wrong?