How do I use SQL in my python code?
Go to solution
Solved by duncannah,
You can use sqlite.
https://docs.python.org/2/library/sqlite3.html
You create a db file, create a table, then add and modify when needed
Here's an example that I made sure works
import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS scores (name text, highscore int)''') conn.commit() ## Get the highscore name = "duncan" # check if row exists c.execute('SELECT 1 FROM scores WHERE name=?', [name]) if c.fetchone() is None: c.execute('INSERT INTO scores VALUES (?, 0)', [name]) conn.commit() highscore = 0 else: c.execute('SELECT highscore FROM scores WHERE name=?', [name]) highscore = c.fetchone() ## Set the highscore highscore = 1 # check if row exists c.execute('SELECT 1 FROM scores WHERE name=?', [name]) if c.fetchone() is None: c.execute('INSERT INTO scores VALUES (?, ?)', [name, highscore]) else: c.execute('UPDATE scores SET highscore=? WHERE name=?', [highscore, name]) conn.commit() ## Close the connection conn.close()
EDIT: Just ran the code, fixed it and it works!
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now