def typeCheckAndConvert(self, val, aname, attr): if val == None: val = "NULL" elif _isIntervalKind(attr): if not isInterval(val): raise TypeError, ( 'trying to assign %s to %s and is not an interval , '\ 'being of type %s ' ) % (val, aname, type(val)) val = _intervalConvertToDB(val) elif _isTimeKind(attr): if not isDateTime(val) and not val == PyDBI.SYSDATE: raise TypeError, ( 'trying to assign %s to %s and is not a time, '\ 'being of type %s ' ) % (val, aname, type(val)) val = _timeConvertToDB(val) elif _isDateKind(attr): if (not isDateTime(val)) and not val == PyDBI.SYSDATE: raise TypeError,( 'trying to assign %s to %s and is not a date, '\ 'being of type %s ' ) % (val, aname, type(val)) val = _dateConvertToDB(val) elif _isNumber(attr): if attr in ('FLOAT4', 'FLOAT8'): f = float elif attr in ('BIGINT', 'INT8'): f = lambda x: long(x) else: f = lambda x: int(float(x)) try: return f(val) except: raise TypeError, ('trying to assign %s to %s and is not' ' a number') % (val, aname) elif _isString(attr) and not isinstance(val, types.StringType): raise TypeError, 'trying to assign %s to %s and is not a string' % ( val, aname) elif _isBinary(attr): return psycopg.Binary(val) elif attr.upper() == 'BOOL': if val: return 'TRUE' else: return 'FALSE' return val
import psycopg, glob conn = psycopg.connect(user='******', password='******', database='subspace') cursor = conn.cursor() for filename in glob.glob('/tmp/ssc/*'): f = open(filename, 'r') data = psycopg.Binary(f.read()) f.close() port = int(filename[filename.find('_') + 1:filename.find('.')]) cursor.execute( 'insert into isometry.sscid (ipaddress, port, sscid) values (inet \'75.101.147.52\', %d, %s)' % (port, data)) conn.commit() cursor.close() conn.close()
for f in timestamp_formats: try: t=time.strptime(val, f) except ValueError: continue else: return psycopg.TimestampFromTicks(time.mktime(t)) else: raise ValueError, "cannot parse timestamp format: '%s'" % val raise ValueError, val _converters={datetime.datetime: lambda x: psycopg.TimestampFromTicks(time.mktime(x.timetuple())), datetime.date: lambda x: psycopg.Date(x.year, x.month, x.day), DATE: convert_DATE, TIMESTAMP: convert_TIMESTAMP, BINARY: lambda x: psycopg.Binary(x.value), INTERVAL: lambda x: x.value} if havemx: # add automatic wrapping for mx.DateTime types _converters[mx.DateTime.DateTimeType]=TimestampFromMx _converters[mx.DateTime.DateTimeDeltaType]=lambda x: x.strftime("%d:%H:%M:%S") class PsycopgConverter(BindingConverter): converters=_converters class PsycopgDBI(DBIBase): def __init__(self, connectArgs, pool=None, verbose=False): if pool and not hasattr(pool, 'connect'): pool=ConnectionPool()
import psycopg, cPickle # Connect to a DB, e.g., the test DB on your localhost, and get a cursor connection = psycopg.connect("dbname=test") cursor = connection.cursor() # Make a new table for experimentation cursor.execute("CREATE TABLE justatest (name TEXT, ablob BYTEA)") try: # Prepare some BLOBs to insert in the table names = 'aramis', 'athos', 'porthos' data = {} for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum, 2) # Perform the insertions sql = "INSERT INTO justatest VALUES(%s, %s)" for name in names: cursor.execute(sql, (name, psycopg.Binary(data[name]))) # Recover the data so you can check back sql = "SELECT name, ablob FROM justatest ORDER BY name" cursor.execute(sql) for name, blob in cursor.fetchall(): print name, cPickle.loads(blob), cPickle.loads(data[name]) finally: # Done. Remove the table and close the connection. cursor.execute("DROP TABLE justatest") connection.close()
def escapeSQLString(self, s): return str(psycopg.Binary(s))[1:-1]
def blobEncode(self, blob): import psycopg return psycopg.Binary(blob)