I'm attempting to let a user which is logged into my flask website, enter a form which outputs an integer, and then they can then view all their output from the form in their profile.
I was thinking that when the user enters out the form, it creates a new table for that specific user and enters the results into that table would that work?
Here is how I generate sqlite3 tables dynamically on the fly, if you do go that route:
def create_table(ptbl):
""" Assemble DDL (Data Definition Language) Table Create statement and build
sqlite3 db table
Args:
string: new db table name.
Returns:
Status string, '' or 'SUCCESS'.
"""
retval = ''
sqlCmd = ''
try:
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
if ptbl == 'TBL_EXAMPLE':
sqlCmd = 'CREATE TABLE IF NOT EXISTS ' + ptbl + ' (FIELD1 TEXT, FIELD2 INTEGER, FIELD3 TEXT, ' \
'FIELD4 TEXT, FIELD5 TEXT)'
else:
pass
if sqlCmd != '':
c.execute(sqlCmd)
conn.commit()
conn.close()
retval = 'SUCCESS'
except Error as e:
retval = 'FAIL'
print(e)
return retval
Related
i want to some of the column of sqlite darabase through one gui window and the rest through another however am getting error
c.execute('INSERT INTO information VALUES(:name,:branch,:reg)',
sqlite3.OperationalError: table information has 6 columns but 3 values were supplied
This is how I create table dynamically on the fly and populate it:
def create_table(ptbl):
""" Assemble DDL (Data Definition Language) Table Create statement and build
sqlite3 db table
Args:
string: new db table name.
Returns:
Status string, '' or 'SUCCESS'.
"""
retval = ''
sqlCmd = ''
try:
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
if ptbl == 'TBL_EXAMPLE':
sqlCmd = 'CREATE TABLE IF NOT EXISTS ' + ptbl + ' (FIELD1 TEXT, FIELD2 INTEGER, FIELD3 TEXT, ' \
'FIELD4 TEXT, FIELD5 TEXT)'
else:
pass
if sqlCmd != '':
c.execute(sqlCmd)
conn.commit()
conn.close()
retval = 'SUCCESS'
except Error as e:
retval = 'FAIL'
print(e)
return retval
and the populate the table having 5 fields like this:
def populate_tbl_file_marker_linenums(p_fml_tbl, p_fml_datafile):
""" Read csv and load data into TBL_FILE_MARKER_LINENUMS table ...
Args:
p_fml_tbl (TEXT) target table name
p_fml_datafile (TEXT) name of csv file to load into table
Returns:
retval (TEXT) - Status of method, e.g., 'SUCCESS'
"""
retval = ''
mode = 'r'
try:
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
csv_dataset = open(p_fml_datafile, mode)
csv_reader = csv.reader(csv_dataset)
c.executemany('INSERT INTO ' + p_fml_tbl + ' (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5) VALUES (?, ?, ?, ?, ?)', csv_reader)
conn.commit()
conn.close()
retval = 'SUCCESS'
except Error as e:
print(e)
return retval
I have a python function in which I want to check if a PostgreSQL table exists or not (True, False)
it does not return True... even when I am logged into the same DB and checking in PGAdmin4.. and getting True.
Am I missing a commit? I tried adding a commit() to no effect.
def __exists_table(self, table_name):
cursor = self.__get_a_cursor()
try:
string_to_execute = "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = '" + table_name + "');"
cursor.execute(string_to_execute)
query_results = cursor.fetchall()
if len(query_results) > 1:
print("__exists_data got back multiple results, using the first")
query_results = query_results[0][0]
return query_results
except Exception as err:
print("Exception on __exists_table: " + str(err))
raise err
finally:
cursor.close()
Your code appears to work as written.
I have a database that contains a single table, table1:
$ psql -h localhost
psql (11.6, server 12.1 (Debian 12.1-1.pgdg100+1))
Type "help" for help.
lars=> \d
List of relations
Schema | Name | Type | Owner
--------+--------+-------+-------
public | table1 | table | lars
(1 row)
If I wrap your code up in a runnable script, like this:
import psycopg2
class DBTest:
def __init__(self):
self.db = psycopg2.connect('host=localhost dbname=lars password=secret')
def __get_a_cursor(self):
return self.db.cursor()
def __exists_table(self, table_name):
cursor = self.__get_a_cursor()
try:
string_to_execute = "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = '" + table_name + "');"
cursor.execute(string_to_execute)
query_results = cursor.fetchall()
if len(query_results) > 1:
print("__exists_data got back multiple results, using the first")
query_results = query_results[0][0]
return query_results
except Exception as err:
print("Exception on __exists_table: " + str(err))
raise err
finally:
cursor.close()
def test_exists_table(self, table_name):
return self.__exists_table(table_name)
db = DBTest()
for table_name in ['table1', 'table2']:
if db.test_exists_table(table_name):
print(f'{table_name} exists')
else:
print(f'{table_name} does not exist')
Running it produces the output I would expect:
table1 exists
table2 does not exist
Having said that, I would make the follow change to your code. First, rather than creating your query string like this:
string_to_execute = """SELECT EXISTS(
SELECT 1 FROM pg_catalog.pg_tables
WHERE schemaname = 'public'
AND tablename = '""" + table_name + "');"
cursor.execute(string_to_execute)
I would let your database driver take care of parameter substitution for you:
string_to_execute = """SELECT EXISTS(
SELECT 1 FROM pg_catalog.pg_tables
WHERE schemaname = 'public'
AND tablename = %s
)"""
cursor.execute(string_to_execute, (table_name,))
This is easier to read and safer, since it will properly quote any special character in the parameter.
I am building a database application as practice. I want to use a set of functions to provide create, update, add, and delete functionality by constructing SQL commands which they will pass to a connector function that will handle the database connection, execute, commit, and close.
I have tried using "SQL command %s", (something)
Also tried the above but with ? instead of %s
This seems to be correct syntax, but is usually included directly into the execute function
import sqlite3
class Connector:
def __init__(self,name):
self.db_name = name
self.table = "book"
def change_table(self,table):
self.table = table
def create_db(self):
command = "CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)"
return self.generic_connector(command)
def insert(self,title,author,year,isbn):
try:
title = str(title)
author = str(author)
isbn = int(isbn)
year = int(year)
command = "INSERT INTO book VALUES(:title,:author,:year,:isbn)",
{"title": title,"author": author,"year": year,"isbn":isbn}
print(command)
return self.generic_connector(command)
except ValueError:
return 1
def generic_connector(self,command):
command = command[0], command[1]
print(command)
try:
conn = sqlite3.connect(self.db_name)
cur = conn.cursor()
cur.execute(command)
rows = cur.fetchall()
conn.commit()
conn.close()
return rows
except (ValueError, SyntaxError):
print("oops")
When I print command, I expected to see :-
"CREATE TABLE IF NOT EXISTS table_name (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)"
Instead, I got this :-
("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)", (self.table,))
I have created the following functions to create a table call user.
import sqlite3
from datetime import datetime
def create_connection(db_file):
try:
connection = sqlite3.connect(db_file)
return connection
except sqlite3.Error as e:
print(e)
return None
def create_table(connection, sql_table):
cursor = connection.cursor()
with connection:
try:
cursor.execute(sql_table)
except sqlite3.Error as e:
print(e)
def insert_user(connection, date, username):
cursor = connection.cursor()
with connection:
cursor.execute("INSERT INTO user VALUES(?,?)",(date, username))
database = "test.db"
user_table = """ CREATE TABLE IF NOT EXISTS user (
date TEXT NOT NULL,
username TEXT NOT NULL
); """
conn = create_connection(database)
create_table(conn, user_table)
date = datetime.now().strftime('%Y-%m-%d')
username = 'user1'
insert_user(conn, date, username)
I would like to make the function insert_user more general. I would like to be able to pass user into this function and not have to explicitly write user in
cursor.execute("INSERT INTO user VALUES(?,?)",(date, username))
Similarly, I would like to avoid explicitly writing user in
user_table = """ CREATE TABLE IF NOT EXISTS user (
Rather I would like to have a variable having the value of user and passing that variable into this statement.
How should I amend my code? Thanks.
I am trying to see whether the type is either a the letter "T" or between number 1-6 for the specific data entry found with name and password.
sql = 'SELECT type FROM table name WHERE name = "{}" AND password = "{}"'.format(username, password)
and then in psedocode i need something like:
if type =< 5:
int()
elif type = "T"
string()
I am using python 2.7
Here is a full script that will query the mysql DB, and use your above-mentioned logic to print the values. I've included the python code as well as the sample database code for this test case. Let me know if you have any questions.
Python
import pymysql
connection = pymysql.connect(user='username', passwd='password',
host='localhost',
database='database')
cursor = connection.cursor()
NAME = 'Person_A'
PASSWORD = 'Password_A'
query = ("SELECT * FROM My_TABLE WHERE NAME = '%(1)s' AND PASSWORD = '%(2)s';" % {"1" : NAME, "2" : PASSWORD})
cursor.execute(query)
for item in cursor:
type = item[0]
if type.isdigit():
if int(type) <6:
print('Type is a number less than 6')
else:
print('Type is a number but not less than 6')
else:
if type == 'T':
print('Type is a string == T')
else:
print('Type is a string but not the letter T')
MYSQL
CREATE TABLE MY_TABLE (TYPE VARCHAR(255), NAME VARCHAR(255), PASSWORD VARCHAR(255));
INSERT INTO MY_TABLE VALUES ('T','Person_A','Password_A'),('4','Person_A','Password_A'),('7','Person_B','Password_B'),('t','Person_C','Password_C');