Check if sql table exists in python [duplicate] - python

This question already has answers here:
How to test if a table already exists?
(4 answers)
Closed 6 years ago.
I am making a python application for a voting system. I am using sqlite3 to create a database which is stored locally on the user's machine.
I need a way to check if a table exists or not because the tables need to get created on each user's database file when they run the application but if the application is run when the tables exist and I just have a statement creating the tables it will run an error because the table already exists.
Here is some simplified sample code
conn = sqlite3.connect('firefight')
c = conn.cursor()
if table 'info' exists:
#do nothing
else:
c.execute("CREATE TABLE info(PRIMARY KEY id int, username text, password text)")

I think there are two options here. First, SQLite has a statement which would create the table only if it does not exist:
CREATE TABLE IF NOT EXISTS info (PRIMARY KEY id int, username text, password text)
But if you want a more database generic way to handle this, you could simply execute a regular CREATE TABLE statement and then handle the exception in Python.

You can execute this SQL:
select count(*) from sqlite_master where type='table' and name='table name'
if you get 1, the table exists, otherwise not exists.

Related

How to create table dynamically from user input? [duplicate]

This question already has answers here:
SQLite: Why can't parameters be used to set an identifier?
(3 answers)
Closed 3 months ago.
I am creating a wishlist app using Tkinter and sqlite3. I want the user to be able to create tables in database by imputing names. For that I connected a button to this function:
def create_table(table_name):
connection = sql.connect(f'{directory}\main.sqlite')
cursor = connection.cursor()
cursor.execute("CREATE TABLE ? (name TEXT, price REAL, url TEXT)",(table_name,))
connection.close()
This doesn't work and I get:
cursor.execute("create table ? (name text, price real, url text)",(table_name,))
sqlite3.OperationalError: near "?": syntax error
Is it possible to do string formatting in CREATE TABLE? I'd rather create separate tables than one with additional column for id of items. I don't want to use f-string as it can be an issue if user inputs commands instead of a name.
Nope, this cannot be done. A table name cannot act as a dynamic parameter from SQLite's point of view. You will need to do something like this:
f'CREATE TABLE {table_name} (name TEXT, price REAL, url TEXT)'
But first you will need to validate the user input for table_name. Which shouldn't be a problem if you want to limit the allowed characters to (for example) only 1+ English letters and 0+ underscores. You might also want to validate the table name length and uniqueness somehow.

How to insert variable to sql table in python if variable is not already in table? [duplicate]

This question already has answers here:
SQLite INSERT - ON DUPLICATE KEY UPDATE (UPSERT)
(5 answers)
Closed 6 months ago.
Im having a problem with my sqlite database in my python program. I'm trying to create a table that will hold records of players score. Player name is saved as variable "val" and that variable is used in sql code. Also if the player is already in my table I don't want to create duplicate.
My problem is that if I don't use WHERE {v}... it all works, but the moment i try to prevent table from creating duplicates it gives me an OperationalError: near "WHERE": syntax error.
Im quite new to sql so it's hard for me to find what i'm doing wrong. I used (?) and format and as long as i don't use WHERE it's fine. How can I make sure that my variable (player name) from outside of sql code is not in my table so i can insert it?
val = "PlayerName"
cur.execute( """
INSERT INTO Table (player_name)
VALUES {v}
WHERE {v} NOT IN (
SELECT player_name FROM Table)""".format(v = val))
Ok, it works now. My main problem was that i tried to use commands from MySQL instead of sqlite. My code that worked:
cur.execute( """INSERT INTO Table (player_name)
VALUES (?)
ON CONFLICT(player_name) DO UPDATE SET player_name= player_name""",(val) )
Edit: Final version without player_name = player_name workaround:
cur.execute( """INSERT OR IGNORE INTO Table (player_name) VALUES (?)""",(val) )

How to check if sqlite db file exists in directory and also check if a table exists using python?

I am trying to append records to a sqlite db file in a table, first checking if the db file exists and then checking if the table exists. If not create the db and table file dynamically.
I hope you are using sqlite3 library, in that if you use connect method it will do exactly what you want.find the db or else create it.
Expanding on to answer by #Umang, you could check for the table's existence using a query as SELECT count(*) FROM sqlite_master WHERE type='table' AND name='table_name';.
What you typically do is simply:
import sqlite3
con = sqlite3.connect('example.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS ...''')
If example.db exists, it'll be used, otherwise it'll be created.
If the table already exists, the CREATE TABLE command will do nothing, otherwise it'll create the table. Done.

How to use variable for SQLite table name [duplicate]

This question already has answers here:
Variable table name in sqlite
(9 answers)
Closed 6 years ago.
I have a program where the user can select what table they want to modify in SQLite. I store the selection in a variable called table, then try and select everything from that table
c.execute('SELECT * FROM ?', (table,))
The program gets stuck at the question mark. It says:
"Sqlite3.OperationalError: near "?": syntax error"
What am I doing wrong?
You can't use parameter substitution for the table name. You need to add the table name to the query string yourself. Something like this:
query = 'SELECT * FROM {}'.format(table)
c.execute(query)
One thing to be mindful of is the source of the value for the table name. If that comes from an untrusted source, e.g. a user, then you need to validate the table name to avoid potential SQL injection attacks. One way might be to construct a parameterised query that looks up the table name from the DB catalogue:
import sqlite3
def exists_table(db, name):
query = "SELECT 1 FROM sqlite_master WHERE type='table' and name = ?"
return db.execute(query, (name,)).fetchone() is not None

insert mysql table from python function

I'm very newbie to python and how its mysql connector works in any web application. I want to try something easy actually but got no idea how to work it out. I have this simple python script to make random numbers and allocate it in a variable. (numbers.py)
import random
number = random.radint(1,1000)
print number
and this very simple python script to make a table in a mysql database (try.py)
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Table_Try")
cur.execute("CREATE TABLE Table_Try(Value INT)")
My question is how do I insert the field "Value" with the value from variable "number" in number.py, since they are different scripts. When the value is inserted, how do I displayed in a php page so it can show random values repeatedly in a endless loop when opened? I have searched tutorial links about this in google but none could answer my problem here.
you can insert values into the database as follows:
c.execute("INSERT INTO db_name.Table(value) VALUES(%s)",[5])
In the above code c is my cursor and Table is my table in that database.
If you want to insert many values you can use executemany instead of execue

Categories