Creating a button to delete data from table in qt - python

Using mysql and python, I have created a table within PyQt that will allow a user to frequently update and track their meeting sessions. The only problem is, I do not know how I would go about coding a button that will allow me to individually delete a row of data.
My table looks like so:
What would be the simplest way to create a button that will appear besides the row of data when new data is inserted that will allow the user to delete that entire row?
Edit:
def deleteRows(self):
items = self.treeWidget.selectedItems()
current = self.treeWidget.currentItem()
for item in items:
sip.delete(current)
self.UpdateTree()
Edit 2:
import mysql.connector
from mysql.connector import errorcode
from datetime import datetime
class DatabaseUtility:
def __init__(self, database, tableName):
self.db = database
self.tableName = tableName
f = open('C:\\Users\\Vlad\\Desktop\\Myfiles\\EnterprisePassport\\password.txt', 'r')
p = f.read(); f.close();
self.cnx = mysql.connector.connect(user = 'root',
password = p,
host = '127.0.0.1')
self.cursor = self.cnx.cursor()
self.ConnectToDatabase()
self.CreateTable()
def ConnectToDatabase(self):
try:
self.cnx.database = self.db
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
self.CreateDatabase()
self.cnx.database = self.db
else:
print(err.msg)
def CreateDatabase(self):
try:
self.RunCommand("CREATE DATABASE %s DEFAULT CHARACTER SET 'utf8';" %self.db)
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
def CreateTable(self):
cmd = (" CREATE TABLE IF NOT EXISTS " + self.tableName + " ("
" `ID` int(5) NOT NULL AUTO_INCREMENT,"
" `date` date NOT NULL,"
" `time` time NOT NULL,"
" `message` char(50) NOT NULL,"
" PRIMARY KEY (`ID`)"
") ENGINE=InnoDB;")
self.RunCommand(cmd)
def GetTable(self):
self.CreateTable()
return self.RunCommand("SELECT * FROM %s;" % self.tableName)
def GetColumns(self):
return self.RunCommand("SHOW COLUMNS FROM %s;" % self.tableName)
def RunCommand(self, cmd):
print ("RUNNING COMMAND: " + cmd)
try:
self.cursor.execute(cmd)
except mysql.connector.Error as err:
print ('ERROR MESSAGE: ' + str(err.msg))
print ('WITH ' + cmd)
try:
msg = self.cursor.fetchall()
except:
msg = self.cursor.fetchone()
return msg
def AddEntryToTable(self, message):
date1 = datetime.now().strftime("%y-%m-%d")
time = datetime.now().strftime("%H:%M")
cmd = " INSERT INTO " + self.tableName + " (date, time, message)"
cmd += " VALUES ('%s', '%s', '%s' );" % (date1, time, message)
self.RunCommand(cmd)
def __del__(self):
self.cnx.commit()
self.cursor.close()
self.cnx.close()
if __name__ == '__main__':
db = 'enterprisepassport'
tableName = 'session'
dbu = DatabaseUtility(db, tableName)

Just add a button at the top that deletes the selected rows. It looks like your using a QTreeWidget
def __init__(...)
...
self.deleteButton.clicked.connect(self.deleteRows)
def deleteRows(self):
items = self.tree.selectedItems()
for item in items:
# Code to delete items in database
self.refreshTable()

#Randomator, why not explain as if you're explaining to a beginner. Even I do not also understand what you're suggesting.
The guy wrote his codes, make corrections in his code so he can easily run the file

Related

AttributeError: 'ChangeDetectorService' object has no attribute 'process'

I'm trying to develop Job program which in turn calls Service program.
ChangeDetectorService does have procedure named process. I don't know why I get the warning message:
AttributeError: 'ChangeDetectorService' object has no attribute 'process'
"change_detector_job.py" and ChangeDetectorService source code are attached.
# change_detector_job.py
import argparse
import datetime
# import multiprocessing
import os
# import sys
# import traceback
import sys
import traceback
from common.utils.config import Config, log_start, log_end
from ReplicationService.module.ChangeDetectorService import ChangeDetectorService
args = None
main_config = None
main_logger = None
app_name = os.path.basename(sys.argv[0]).replace('.py', '') + '_main'
class ChangeDetectorJob:
def __init__(self):
self.config = None
self.logger = None
self.env = 'test'
def setup(self):
self.env = args.env
self.config = Config(args.config, app_name)
self.logger = self.config.get_logger()
def process(self):
self.setup()
t1 = log_start("ChangeDetector job started (UTC): %s" % (datetime.datetime.utcnow()), with_memory=True,
logger=self.logger)
service = ChangeDetectorService(args.config, app_name)
success = service.process()
log_end("ChangeDetector job completed (UTC): %s" % (datetime.datetime.utcnow()), success=success, start_time=t1,
logger=self.logger)
if __name__ == '__main__':
try:
parser = argparse.ArgumentParser(description="Data ChangeDetector Job")
parser.add_argument("-e", "--env", default="test", choices=['test', 'dev', 'uat', 'prd'],
help="environment this job to be deployed (default %default)")
parser.add_argument("-c", "--config", default="../config/cmo_backend_local_config.ini",
help="config file (test only default %default)")
args = parser.parse_args()
ini_file = args.config
main_config = Config(ini_file, app_name)
main_logger = main_config.get_logger()
# multiprocessing.set_start_method('spawn')
main_logger.info("**** ChangeDetector job started (UTC): %s" % datetime.datetime.utcnow())
# service = ChangeDetectorService(args.config, app_name)
# success = service.process()
ChangeDetectorJob().process()
main_logger.info("**** ChangeDetector job completed (UTC): %s" % datetime.datetime.utcnow())
except Exception as error:
if main_logger is not None:
main_logger.error("Exception encountered: " + str(error))
main_logger.error(traceback.format_exc())
traceback.print_exc()
print("FINAL EXCEPTION OUT .... ")
# ChangeDetectorService.py
# import mysql.connector
from datetime import datetime
from datetime import timedelta
from common.database.mysql_manager import MysqlManager
from common.utils.config import Config, log_start, log_end
# mysql.connector.connect(host='localhost',port="3306",user='user',password='pass',database='dbname')
import mysql.connector
# rows_inserted = 0;
class ChangeDetectorService:
#
def __init__(self, ini_file, app_name):
self.config_object = Config(ini_file, app_name)
self.logger = self.config_object.get_logger()
self.mysql_manager = MysqlManager(self.config_object)
try:
def get_connection(self):`enter code here`
connection = mysql.connector.connect(user='user', password='zzzz',
host='host',
database='dbname'
)
return connection
def init_change_detector(self):
print("Change Detector started at " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
mysqlManager = MysqlManager
# conn = self.get_connection()
conn = self.mysqlManager.get_db_connection()
cursor = conn.cursor()
query = ('SELECT table_name, column_name, key_name '
'FROM cmooptimizationsvc.csj_chngdtct_tab_col '
'WHERE is_active=1 '
'ORDER BY table_name, column_name')
cursor.execute(query)
# get all records
records = cursor.fetchall()
for record in records:
self.process_col_tab_chg(record[0], record[1], record[2])
if conn.is_connected():
conn.close()
cursor.close()
def insert_change_log(self, table_name, key_name, attr_name, old_attr_value, new_attr_value):
# global rows_inserted;
insert_query = """INSERT INTO csj_shipment_changelog(table_name, key_name,
attr_name, old_attr_value,
new_attr_value)
VALUES (%s, %s, %s, %s, %s)"""
conn = self.get_connection()
cursor = conn.cursor()
tuple1 = (table_name, key_name, attr_name, old_attr_value, new_attr_value)
# tuples.append(tuple1)
cursor.execute(insert_query, tuple1)
# rows_inserted += 1
# print( rows_inserted );
# if (rows_inserted%10==0):
# cursor.executemany(insert_query, tuples)
conn.commit()
rows_inserted = 0
# tuples = []
# quit()
cursor.close()
conn.close()
# Look for Shipment, in past date
def find_past_shipment(self,
table_name,
key_name,
column_name,
before_date,
curr_key
):
saved_col_name = column_name
saved_key_name = key_name
conn = self.get_connection()
cursor = conn.cursor()
query = 'SELECT ' + saved_key_name + ' , ' + saved_col_name + ' FROM ' + table_name \
+ ' where rec_cre_dt_utc < ' + "'" + before_date.strftime('%Y-%m-%d 00:00:00') + "'" \
+ ' and shipment_num = ' + "'" + curr_key + "'" + ' order by rec_cre_dt_utc desc LIMIT 1'
cursor.execute(query)
records = cursor.fetchone()
cursor.close()
conn.close()
if records is not None:
past_attr_val = records[1]
return past_attr_val
else:
return 0
def process_col_tab_chg(self,table_name, column_name, key_name):
saved_key_name = key_name
saved_col_name = column_name
old_val = 0
ini_time_for_now = datetime.now()
date_before_1day = ini_time_for_now - timedelta(days=1)
query = 'SELECT ' + key_name + ' , ' + saved_col_name + ' , ' + ' rec_cre_dt_utc FROM ' + table_name \
+ ' where rec_cre_dt_utc >= ' + "'" + date_before_1day.strftime('%Y-%m-%d 00:00:00') + "'"
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute(query)
for (key_name, column_name, rec_cre_dt_utc) in cursor:
curr_attr_val = column_name
curr_key_val = key_name
old_val = self.find_past_shipment(table_name,
saved_key_name,
saved_col_name,
rec_cre_dt_utc,
curr_key_val
)
if curr_attr_val != old_val \
and old_val != 0:
self.insert_change_log(table_name, key_name, saved_col_name, old_val, curr_attr_val )
else:
continue
cursor.close
conn.close()
def cleanup():
print("Change Detector stopped " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def process():
start = datetime.now()
init_change_detector()
# cleanup()
# mysqlManager = MysqlManager
# conn = get_connection(self)
# conn = self.mysql_manager.get_db_connection()
# cursor = conn.cursor()
# query = ('SELECT table_name, column_name, key_name '
# 'FROM cmooptimizationsvc.csj_chngdtct_tab_col '
# 'WHERE is_active=1 '
# 'ORDER BY table_name, column_name')
# cursor.execute(query)
# # get all records
# records = cursor.fetchall()
# for record in records:
# self.process_col_tab_chg(record[0], record[1], record[2])
# if conn.is_connected():
# conn.close()
# cursor.close()
end = datetime.now()
time_diff = (end - start)
execution_time = time_diff.total_seconds()
print("Elapsed time(secs): " + str(execution_time))
except Exception as e:
print("Exception " + e)
finally:
cleanup()
# if __name__ == "__main__":
# main()
You get AttributeError when you try to use an attribute (method or property) which does not exist for your object (class). In this case, the error states that ChangeDetectorService is under the question:
AttributeError: 'ChangeDetectorService' object has no attribute 'process'
In your error message, right before the above line, you should see the code line which caused this error:
success = service.process()
service was assigned to this expression:
service = ChangeDetectorService(args.config, app_name)
So, service is of type (class) ChangeDetectorService. It must be it... Inspecting the source code we see this:
class ChangeDetectorService:
#
def __init__(self, ini_file, app_name):
self.config_object = Config(ini_file, app_name)
self.logger = self.config_object.get_logger()
self.mysql_manager = MysqlManager(self.config_object)
try:
...
try has the same indentation as class. So, try has closed the ChangeDetectorService class definition. It means, your ChangeDetectorService class has only the constructor (__init__) defined. ChangeDetectorService class does not have any other method defined. It means, it doesn't have process method either. That's why you get the error. If you want ChangeDetectorService class to have the process method, make sure try or anything else does not interfere with all the method definitions of the class.

Not able to show sqlite3(back end) error on Tkinter(front end)

I am working on a small project which is a school management project which simply does add, update, delete a student from the database
For the front end I am using Tkinter and for backend I am using sqlite3
Here I have roll number as the primary key, when I try to add the same roll number again it doesn't add into the database, and also it doesn't return anything on the front end.
So, I try to add showerror on the front end from the already exists roll number but it doesn't give me an error on the front end. For update and delete it showing an error on the font-end properly but for add only it is not working
Here is the code of save function(which is not working properly):
def save1():
con = None
try:
Connection.cursor
con = connect("pypro.db")
try:
rollno = int(enteno.get())
name = entename.get()
marks = int(entmrk.get())
except:
messagebox.showerror("EMPTY","enter the entry properly")
try:
if len(name)<2:
return messagebox.showerror("ERROR","name should contain minimum 2 alphabets")
if marks > 101:
return messagebox.showerror("ERROR","marks should be less the 100")
finally:
entmrk.delete(0,END)
cursor = con.cursor()
sql = "insert into entry values ('%d','%s','%d')"
args = (rollno,name,marks)
cursor.execute(sql%args)
if cursor.rowcount == 1:
con.commit()
msg = "RECORD Inserted"
messagebox.showinfo("Inserted",msg)
else :
msg2 = "record does exists"
return messagebox.showerror("ERROR",msg2)
enteno.delete(0,END)
entename.delete(0,END)
entmrk.delete(0,END)
enteno.focus()
except DatabaseError as e:
con.rollback()
finally:
if con is not None:
con.close()
Here is the code of update function(which is working properly):
def update():
con = None
try:
Connection.cursor
con = connect("pypro.db")
try:
name = enteupname.get()
marks = int(entupmrk.get())
except:
messagebox.showinfo("EMPTY","enter the entry properly")
try:
if len(name)<2:
return messagebox.showerror("ERROR","name shoul contain minimum 2 alphabets")
if marks >= 100:
return messagebox.showerror("ERROR","marks should be less the 100")
finally:
entmrk.delete(0,END)
rollno = int(entupeno.get())
cursor = con.cursor()
sql = "update entry set name='%s'where rollno= '%d'"
args = (name,rollno)
cursor.execute(sql % args)
sql1 = "update entry set marks='%d' where rollno='%d'"
args1 = (marks,rollno)
cursor.execute(sql1%args1)
if cursor.rowcount == 1:
con.commit()
msg = "RECORD UPDATED"
messagebox.showinfo("update",msg)
else:
msg = "record does not exists"
messagebox.showerror("ERROR",msg)
entupeno.delete(0,END)
enteupname.delete(0,END)
entupmrk.delete(0,END)
entupeno.focus()
except DatabaseError as f:
con.rollback()
finally:
if con is not None:
con.close()
Please tell me if more information need to be added in this question.

Python-MySQL query does not showing results including the previous import in same query

I have a function what is adding new records in to Mysql database after scanning a barcode. Function is working but there is a problem with returning result on the App screen.
When I scan the barcode first time it does not return any results even when i can see that the new record was created. But when i scan the barcode second time it returns only 1 record.
Edit:(added more about the issue)
And after that it is always -1 record, which would not be problem i could add +1 to all results but the problem is the first one, as it returns nothing at all.
I tried to use time.sleep(.3) between the queries but that did not have any effect.
I now wonder if the Python code is wrong or my SQL query should be somehow different.
def db_execute3(config, sql, val):
mydb = mysql.connector.connect(**config)
mycursor = mydb.cursor()
try:
mycursor.execute(sql, val)
mydb.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.CR_CONN_HOST_ERROR:
popip.open()
Clock.schedule_once(popip.dismiss, 3)
elif err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
popx.open()
Clock.schedule_once(popx.dismiss, 3)
elif err.errno == errorcode.ER_BAD_DB_ERROR:
popdb.open()
Clock.schedule_once(popdb.dismiss, 3)
elif err.errno == errorcode.ER_NO_REFERENCED_ROW_2:
popbr.open()
Clock.schedule_once(popbr.dismiss, 3)
else:
mycursor.close()
def inbsort_btndwn(self, _):
cont = self.container_no.text.upper()
barc = self.sku_barcode.text.upper()
sort_worknumb = self.sort_worknumb.text.upper()
val = (sort_worknumb, cont, barc)
valx = (cont,barc)
if barc is "" and cont is "":
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
Clock.schedule_once(self.focus_container_no, 0.2)
elif barc is "" and cont is not "":
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
Clock.schedule_once(self.focus_sku_barcode, 0.2)
else:
try:
mydb = mysql.connector.connect(**config)
checkupd = mydb.cursor(prepared=True)
sqlq = "select * from inb_container where `container_no` = %s and `sku_code` = %s;"
checkupd.execute(sqlq, valx)
record = checkupd.fetchone()
if record is None:
errorsound.play()
popuni.content.text = "No records for scanned Barcode!"
popuni.open()
Clock.schedule_once(popuni.dismiss, 2)
Clock.schedule_once(self.clear_barcode, .2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)
else:
correctsound.play()
sql = "INSERT INTO inb_sor_con (`work_number`, `container_no`,`sku_barcode`) VALUES (%s, %s, %s)"
db_execute3(config, sql, val)
sqlz = "SELECT ic.sort_box,ic.sort_pallet FROM inb_container ic, " \
"inb_sor_con ib WHERE ic.container_no =ib.container_no and ic.sku_code = ib.sku_barcode " \
"and ic.container_no = %s and ic.sku_code = %s"
valz = (cont, barc)
checkupd.execute(sqlz, valz) #v289-ukan1012044-n10 #msku8416005
myresult = checkupd.fetchall()
for row in myresult:
xxx = "Scanned: {} of: {}".format(checkupd.rowcount, row[0])
zzz = "{}".format(row[1])
self.pallet_sku.text = zzz
self.number_sku.text = xxx
Clock.schedule_once(self.clear_barcode, 0.2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)
except mysql.connector.Error as err:
print(err.errno)
pass
This is the database:
create table inb_container(
`container_no` varchar(25) NOT NULL,
`sku_code` varchar(40) NOT NULL,
`sort_box` int(5),
`sort_pcs` int(6),
`sort_pallet` varchar(3),
Unique (container_no,sku_code)
);
create table inb_sor_con(
`id_scan` int(6) auto_increment not null primary key,
`work_number` varchar(12),
`container_no` varchar(25) NOT NULL,
`sku_barcode` varchar(40) NOT NULL,
`sort_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (work_number) REFERENCES user_logins(work_number),
FOREIGN KEY (container_no) REFERENCES inb_container(container_no));
As mentioned, I'd suggest refactoring your code so it's not mixing UI code with database access. That way you can more easily test each bit of your program (either manually, from a separate module) or automatically using unit tests or such.
You can also freely create new cursors, don't reuse a single one.
Here's one such refactoring...
def find_container(db, *, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"select * from inb_container where `container_no` = %s and `sku_code` = %s",
(container_no, barcode),
)
return cursor.fetchone()
def insert_sor_con(db, *, sort_worknumb, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"INSERT INTO inb_sor_con (`work_number`, `container_no`,`sku_barcode`) VALUES (%s, %s, %s)",
(sort_worknumb, container_no, barcode),
)
db.commit()
def get_scan_results(db, *, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"""
SELECT ic.sort_box,ic.sort_pallet
FROM inb_container ic, inb_sor_con ib
WHERE (
ic.container_no = ib.container_no AND
ic.sku_code = ib.sku_barcode AND
ic.container_no = %s AND
ic.sku_code = %s
)""",
(container_no, barcode),
)
return cursor.fetchall()
def show_error(message):
errorsound.play()
popuni.content.text = message
popuni.open()
Clock.schedule_once(popuni.dismiss, 2)
class SomeUI:
def inbsort_btndwn(self, _):
container_no = self.container_no.text.upper()
barcode = self.sku_barcode.text.upper()
sort_worknumb = self.sort_worknumb.text.upper()
if not (barcode and container_no):
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
if not barcode:
Clock.schedule_once(self.focus_sku_barcode, 0.2)
else:
Clock.schedule_once(self.focus_container_no, 0.2)
return
try:
with mysql.connector.connect(**config) as mydb:
container_record = find_container(
mydb, container_no=container_no, barcode=barcode
)
if container_record:
correctsound.play()
insert_sor_con(
mydb,
sort_worknumb=sort_worknumb,
container_no=container_no,
barcode=barcode,
)
scan_results = list(
get_scan_results(mydb, container_no=container_no, barcode=barcode)
)
for sort_box, sort_pallet in scan_results:
self.pallet_sku.text = "{}".format(sort_pallet)
self.number_sku.text = "Scanned: {} of: {}".format(
len(scan_results), sort_box
)
else:
show_error("No records for scanned Barcode!")
except Exception as exc:
# may want to use `traceback.print_traceback()` here for more detail
print(exc)
show_error(f"Error: {exc}")
Clock.schedule_once(self.clear_barcode, 0.2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)

Need Python Programming Tips

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()

Python psycopg2 set constraint deferrable

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__.

Categories