And so I have this Python file ( dosql.py ):
import sys
import psycopg2
class doSql(object):
#attributes
_cxn = ""
_cur = ""
errmsg =""
#methods
def __init__(self): #constructor
self._cxn = psycopg2.connect("dbname='postgres' user='postgres' password='4scoreand7yearsago' host='127.0.0.1' port='5432'")
self._cur = self._cxn.cursor()
def __del__(self): #destructor
self._cur.close()
self._cxn.close()
def execqry(self, sql, apply_):
rows = []
try:
self._cur.execute(sql)
rows = self._cur.fetchall()
if apply_:
self._cxn.commit()
if self._cur.rowcount == 0:
rows.append(['None'])
except:
#errmsg = sys.exc_type + ":" + sys.exc_value
errmsg = str(sys.exc_info()[1])
rows.append([errmsg])
return rows
In pgAdmin through the Query Tool, I already have a table with the predefined data in the database ' postgres '.
CREATE TABLE misc (
id int primary key,
col1 text,
col2 text
);
INSERT INTO misc VALUES (1, 'yes', 'i', 'entered');
To which in the cmd, I try to execute inside the Python interpreter (with respect to the directory of the file):
>>> execfile('dosql.py')
>>> a = doSql()
>>> i = a.execqry("SELECT * FROM misc", False)
>>> print i
[(1, 'yes', 'i', 'entered')]
>>> f = a.execqry("INSERT INTO misc VALUES (2, 'please', 'just', 'enter')", True)[0][0]
>>> print f
no results to fetch
>>> g = a.execqry("SELECT * FROM misc", False)
>>> print g
[(1, 'yes', 'i', 'entered'), (2, 'please', 'just', 'enter')]
But when I go check pgAdmin and browse the table, it doesn't update to 2 rows , still only has 1, (the [1, 'yes', 'i', 'entered'] data).
Does this mean that the self._cxn.commit() didn't work? Also when I try to redo the whole process again and then initialize the destructor through del a , still to no avail, no updated table.
Any help please?
The code pass False
for apply_
parameter; which result no commit
call.
a.execqry("INSERT INTO ......", False)
^^^^^
Try the code with True
argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.