I am trying to create a database using python. When the program runs no error occurs, however nothing happens. Is there a line I am missing?
class create_db:
def __init__(self):
self.conn = sqlite3.connect("EXAMPLE.db")
self.c = self.conn.cursor()
def create_tables(self, Tables):
for table_name, field in Tables.items():
self.c.execute('CREATE TABLE IF NOT EXISTS ' + table_name + '(' + field + ')')
self.conn.commit()
def main():
db = create_db()
tables = {"CUSTOMERS": '''CustomerID integer,
Customer_Name text,
primary key (CustomerID)'''}
db.create_tables(tables)
main()
Related
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying the following python code:
import sqlite3
class database:
def __init__(self):
self.conn = sqlite3.connect("warehousedb.db")
self.cursor = self.conn.cursor()
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS `admin` (admin_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT)")
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS `product` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
self.cursor.execute("SELECT * FROM `admin` WHERE `username` = 'admin' AND `password` = 'admin'")
if self.cursor.fetchone() is None:
self.cursor.execute("INSERT INTO `admin` (username, password) VALUES('admin', 'admin')")
self.conn.commit()
def __del__(self):
self.cursor.close()
self.conn.close()
def Execute_SQL(self, sql):
self.cursor.execute(sql)
self.conn.commit()
def Get_SQL(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def Get_SQL_One_Rec(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchone()
Then when trying this code:
db = database()
st = "SELECT * FROM `admin` WHERE `username` = '" + USERNAME.get() + "' AND `password` = '" + PASSWORD.get() + "'"
rec = db.Get_SQL_One_Rec(st)
I am getting the following error:
rec = db.Get_SQL_One_Rec(st)
TypeError: Get_SQL_One_Rec() missing 1 required positional argument: 'sql'
I can see from the Python Documentation that the Self object is automatically passed, so why I am getting this error?
The code you have provided works, see this link:
https://repl.it/#zlim00/self-is-not-passed-to-the-class-method-in-python
The only difference compared to your code is that this sqllite database is in memory instead of a file. So if the code doesn't work for you, the error lies in parts of the code that you have not submitted.
Code (in case the link is removed):
import sqlite3
class database:
def __init__(self):
self.conn = sqlite3.connect(":memory:")
self.cursor = self.conn.cursor()
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS `admin` (admin_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT)")
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS `product` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
self.cursor.execute("SELECT * FROM `admin` WHERE `username` = 'admin' AND `password` = 'admin'")
if self.cursor.fetchone() is None:
self.cursor.execute("INSERT INTO `admin` (username, password) VALUES('admin', 'admin')")
self.conn.commit()
def __del__(self):
self.cursor.close()
self.conn.close()
def Execute_SQL(self, sql):
self.cursor.execute(sql)
self.conn.commit()
def Get_SQL(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def Get_SQL_One_Rec(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchone()
if __name__ == '__main__':
db = database()
st = "SELECT * FROM `admin` WHERE `username` = '" + 'admin' + "' AND `password` = '" + 'admin' + "'"
rec = db.Get_SQL_One_Rec(st)
print(rec)
I'm learning python since last few weeks. For better learning, I decided to work on some project. So here is my Class for MySQL connection and demo example as well. Can you please tell me. What other improvement can be possible for following code?
Structure?
What else I can do to optimize code?
And Please forgive. If I'm doing some silly mistakes in code. (I'm learning)
#!/usr/bin/python
import pymysql
# select (table, parameter)
# insert (table, data)
# update (table, id, data)
# delete (table, id)
class MySQL:
def __init__(self):
self.sort_by = ""
self.order = ""
# initiate database connection.
self.connection = pymysql.connect(host='localhost',
user='root',
password='',
db='sherlock',
charset='utf8mb4')
self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
# this function is for selecting any feild on any table.(feilds veriable is optinal)
def select(self, table, *feilds):
flds = "" #differnt name for feilds veriable.
if not feilds:
flds = '*'
else:
for f in feilds:
if not flds:
flds = f
else:
flds += ",`%s`" % f
sql = "SELECT %s FROM `%s` " % (flds, table)
if self.sort_by:
sql = sql +"order by "+ str(self.sort_by) +" "+ str(self.order)
print sql
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
# This function is for data sorting for Mysql; but optinal.
# example : SELECT * FROM `users` order by id asc
def order_by(self, sort_by="", order="", *args, **kwargs):
self.sort_by = sort_by
self.order = order
# this function is for closing Mysql connection
def close(self):
self.connection.close()
########### END OF MySQL CLASS #############
sql = MySQL()
# sql.order_by function should be called before the sql.select() function.
sql.order_by("email")
# this will select all the feilds from `users` table.
# you can specify whichever feilds you want to return. like : sql.select("users", "id, email")
result = sql.select("users", "password")
for email in result:
print email["password"]
sql.close()
I have the class below to handle my Postgres DB and I'm running into trouble with multiple inserts where foreign keys are involved. If I insert first in a parent table and then a child table I get a foreign key violation error although I think I have all the deferrable things in place. (autocommit is not enabled)
The constraint on the foreign key is set as follows:
CONSTRAINT tblorganisations_status_tblorganisations_fkey FOREIGN KEY (org_id)
REFERENCES organisations.tblorganisations (org_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY IMMEDIATE;
The code that calls the class:
postgres = Postgresql("organisations")
r = postgres.insert(self.db_table, data, return_cols='org_id')
self.org_id = r['org_id']
postgres.insert('tblorganisations_status',
{'org_id': self.org_id,
'org_status_id': 'NEW_CGM'})
postgres.commit()
And the class:
class Postgresql():
conn = None
cur = None
last_result = None
def __init__(self, schema=None):
reload(sys) # Reload does the trick!
sys.setdefaultencoding("utf-8")
self.log = Log()
self.connect()
if schema is not None:
self.schema = schema
self.set_default_schema(schema)
def connection_string(self):
return 'host=%s port=%s dbname=%s user=%s password=%s' % \
(get_config('DATABASE', 'host'),
get_config('DATABASE', 'port'),
get_config('DATABASE', 'dbname'),
get_config('DATABASE', 'user'),
get_config('DATABASE', 'password'))
def connect(self):
try:
self.conn = psycopg2.connect(self.connection_string())
self.conn.set_session(isolation_level='read uncommitted', deferrable=True)
self.cur = self.conn.cursor(cursor_factory=RealDictCursor)
except Exception, e:
self.log.error(e.message)
raise
def set_default_schema(self, schema):
try:
self.cur.execute("SET search_path TO %s,public;", (schema, ))
except Exception, e:
self.log.error(e.message)
raise
def commit(self):
self.conn.commit()
self.close()
def rollback(self):
self.conn.rollback()
self.close()
def close(self):
self.cur.close()
self.conn.close()
def insert(self, table, data, return_cols=None, **kwargs):
data = self.cleanup_data(table, data)
fields = data.keys()
if self.schema is not None:
table = self.schema + '.' + table
sql = "INSERT INTO " + table + " ("
sql += ",".join(fields) + ") VALUES (" + ",".join(["%s"]*len(fields)) + ")"
if return_cols:
sql += " RETURNING " + return_cols
sql += ";"
if 'debug' in kwargs:
raise Exception(sql % tuple(data.values()))
try:
self.log.event('POSTGRES: ' + (sql % tuple(data.values())))
self.cur.execute(sql, data.values())
if return_cols:
result = self.cur.fetchone()
return result
except Exception, e:
self.log.error(e.message)
self.conn.rollback()
self.close()
raise
`
I figured it out myself. Apparently psycopg2 behaves this way because I declared the connection and class variables outside __init__.
I have a class as below that I'm using to connect to a remote SQL server instance from a linux server python web app. I define and set cursor in the init constructor and wish to use it throughout the class. How do I do this? I come form a java background and don't understand the scope and protection levels of Python fields.
import pyodbc
class SQLSeverConnection():
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
connection = pyodbc.connect(connectionString)
cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = cursor.fetchall()
return data
def getColumnTitles(self, tableName):
cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position')
columns = cursor.fetchall()
return columns
def getTableNames(self):
cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE''')
tables = cursor.fetchall()
return tables
The answer is simple: Python's "methods" are really plain functions, and local variables are plain local variables. To set / access instance attributes, you must use the current instance, which is passed as first argument to the function (and by convention named self):
class SQLSeverConnection():
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
self.connection = pyodbc.connect(connectionString)
self.cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
self.cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = self.cursor.fetchall()
return data
def getColumnTitles(self, tableName):
self.cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position')
columns = self.cursor.fetchall()
return columns
def getTableNames(self):
BASE_TABLE ='BASE_TABLE'
self.cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'')
tables = self.cursor.fetchall()
return tables
Now using a single shared cursor for all operations is brittle, you'd better instanciate a new cursor for each operation. Also, since a cursor is an iterable, you may want to return the cursor itself and let client code iterate over it, it might save some memory...
class SQLSeverConnection(object):
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
self.connection = pyodbc.connect(connectionString)
def getCursor(self):
return self.connection.cursor()
def getColumnData(self, columnName, tableName):
cursor = self.getCursor()
cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
return cursor
# etc
Oh and yes: using mixCased is not pythonic, we prefer all_lower ;)
change cursor to self.cursor
def __init__(self, DSN, user, password, database):
connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database)
connection = pyodbc.connect(connectionString)
self.cursor = connection.cursor()
def getColumnData(self, columnName, tableName):
self.cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp')
data = self.cursor.fetchall()
return data