python连接postgresql数据库
連接postgresql數據庫
pip install psycopg2
## 導入psycopg2包
import psycopg2
## 連接到一個給定的數據庫
conn = psycopg2.connect(database="postgres", user="postgres",
? ? ? ? ? ? ? ? ? ? ? ? password="postgres", host="127.0.0.1", port="23333")
## 建立游標,用來執行數據庫操作
cursor = conn.cursor()
## 執行SQL命令
cursor.execute("DROP TABLE test_conn")
cursor.execute("CREATE TABLE test_conn(id int, name text)")
cursor.execute("INSERT INTO test_conn values(1,'haha')")
## 提交SQL命令
conn.commit()
## 執行SQL SELECT命令
cursor.execute("select * from test_conn")
## 獲取SELECT返回的元組
rows = cursor.fetchall()
for row in rows:
? ? print 'id = ',row[0], 'name = ', row[1], '\n'
## 關閉游標
cursor.close()
## 關閉數據庫連接
conn.close()
參數化查詢
#list參數化查詢
#sql = "select * from pg_tables where schemaname=%s and tablename=%s"
#csor.execute(sql, ['internal_app_bsaata', 'event_ip_real'])
#dict參數化查詢
sql = "select * from pg_tables where schemaname=%(db_name)s and tablename=%(tb_name)s"
csor.execute(sql, {'db_name':'internal_app_bsaata', 'tb_name':'event_ip_real'})
##多條數據處理
namedict = ({"first_name":"Joshua", "last_name":"Drake"},
? ? ? ? ? ? {"first_name":"Steven", "last_name":"Foo"},
? ? ? ? ? ? {"first_name":"David", "last_name":"Bar"})
cur = conn.cursor()
cur.executemany("""INSERT INTO bar(first_name,last_name) VALUES (%(first_name)s, %(last_name)s)""", namedict)
?
注意:sql執行失敗后,需要回滾才能繼續執行后面的sql
try:## 執行SQL命令dbconn.cursor.execute(sql)## 提交SQL命令dbconn.conn.commit()except Exception as e:dbconn.conn.rollback()logging.exception(e) # 方式2
-----------自己寫的dbhelper.py
總結
以上是生活随笔為你收集整理的python连接postgresql数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分页器 版本控制
- 下一篇: UDLD(Unidirectional