簡介
Psycopg 是Python語言的PostgreSQL數據庫接口。 它的主要優勢在於完全支持Python DB API 2.0,以及安全的多線程支持。它適用於隨時創建、銷毀大量游標的、和產生大量並發INSERT、UPDATE操作的多線程數據庫應用。Psycopg包內含 ZPsycopgDA,一個Zope數據庫接口。
示例1:新建表、插入、修改
#-*- coding: utf-8 -*- import psycopg2 def main(user,pwd,ip,port,dbname): connection = "dbname=%s user=%s password=%s host=%s port=%s" % (dbname, user,pwd, ip, port) db = psycopg2.connect(connection) cur = db.cursor() #創建表 sql_stat = "CREATE TABLE test_class_id(id INT PRIMARY kEY NOT NULL, test_class TEXT, test_id CHAR(10))"; cur.execute(sql_stat) #插入表 sql_stat = "insert into test_class_id(id, test_class, test_id) values (1, 'a', '3')" cur.execute(sql_stat) sql_stat = "insert into test_class_id(id, test_class, test_id) values (2, 'a', '3')" cur.execute(sql_stat) #更改字段值 sql_stat = "update test_class_id set test_class='b' where id=1" cur.execute(sql_stat) db.commit() if __name__ == "__main__": user = '****' pwd = '****' ip = '***' port = '5432' dbname = '****' main(user, pwd, ip, port, dbname) print "Done~~"
結果
注:這里有多次提交execute 最后一次提交commit,如果沒有最后的一次commit,你們前面的提交也是不執行的。
示例2:批量表操作
-*- coding: utf-8 -*- import psycopg2 class_ids = [] class_ids.append({"test_id": 1, "test_class":"A", "test_id":"1"}) class_ids.append({"test_id": 2, "test_class":"A", "test_id":"2"}) class_ids.append({"test_id": 3, "test_class":"B", "test_id":"3"}) def main(user,pwd,ip,port,dbname): connection = "dbname=%s user=%s password=%s host=%s port=%s" % (dbname, user,pwd, ip, port) db = psycopg2.connect(connection) cur = db.cursor() #sql_del = "delete from cdb_chk_group" #cur.execute(sql_del) #批量操作 sql_stat = 'insert into test_class_id(id, test_class, test_id) values (%(test_id)s, %(test_class)s,%(test_id)s)' cur.executemany(sql_stat, class_ids) db.commit() if __name__ == "__main__": user = '****' pwd = '****' ip = '****' port = '5432' dbname = '****' main(user, pwd, ip, port, dbname) print "Done~~"
驗證
用法補充
1. 查詢數據,並輸出結果
查詢一條
>>> cur.execute("select * from test;") >>> cur.fetchone() (1, 100, "abc'def")
查詢所有條
>>> cur.execute("select * from test;") >>> cur.fetchall() [(1, 100, "abc'def"),(2, 100, "abc'def")]