過程:python
connection對象負責管理事務。當你第一次使用cursor.execute方法執行sql語句的時候事務開啓,這之後的全部sql語句都在這個事務中執行,直到connection.commit或者connection.rollback或者del connection或者connection.close被調用,事務才結束。sql
一個簡單的select語句可能會開啓一個事務而且對相應的表格加鎖,因此若是你是在開發一個長時間運行的應用,並且一個鏈接長時間不使用,那麼你須要調用commit或者rollback方法結束事務,避免沒必要要的問題。數據庫
使用connection.autocommit來控制事務函數
從psycopg2.5開始,connection和cursor都是context manager對象,能夠在with ... as ...語句中使用。值得注意的是,離開with語句後,connection對象不會被close,它只是結束提交或者回滾事務。因此能夠在多個with語句中使用connection對象。post
如下這個例子演示了二進制數據的存取。fetch
config.pypostgresql
def config(): db_conn_config = { 'host': 'localhost', 'user': 'postgres', 'password': '', 'dbname': 'test', 'port': 5432 } return db_conn_config
import psycopg2 from config import config def write_blob(path_to_file): """ insert a BLOB into a table """ conn = None try: # read data from a picture drawing = open(path_to_file, 'rb').read() # read database configuration params = config() # connect to the PostgresQL database conn = psycopg2.connect(**params) # create a new cursor object cur = conn.cursor() # execute the INSERT statement cur.execute("INSERT INTO parts_drawings(drawing_data,name) " + "VALUES(%s,%s)", (psycopg2.Binary(drawing), path_to_file)) # commit the changes to the database conn.commit() # close the communication with the PostgresQL database cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': write_blob('./1.jpg')
from config import config import psycopg2 def read_blob(id, path_to_dir): """ read BLOB data from a table """ conn = None try: # read database configuration params = config() # connect to the PostgresQL database conn = psycopg2.connect(**params) # create a new cursor object cur = conn.cursor() # execute the SELECT statement cur.execute(""" SELECT * FROM parts_drawings WHERE id = %s """, (id,)) blob = cur.fetchone() open(path_to_dir + str(blob[0]) + '.jpg', 'wb').write(blob[1]) # close the communication with the PostgresQL database cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': read_blob(1, './img/')