日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python连接postgresql数据库

發布時間:2023/12/10 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

# coding:utf-8 import loggingimport psycopg2def dbconn(config):dbconn.conn = psycopg2.connect(database=config["database"], user=config["user"],password=config["password"], host=config["host"],port=config["port"])## 建立游標,用來執行數據庫操作dbconn.cursor = dbconn.conn.cursor()def exec_sql(sql):#print sqltry:## 執行SQL命令dbconn.cursor.execute(sql)## 提交SQL命令dbconn.conn.commit()except Exception as e:dbconn.conn.rollback()logging.exception(e) # 方式2def exec_sql_muti(sql,params):#print sqltry:## 執行SQL命令dbconn.cursor.executemany(sql,params)## 提交SQL命令dbconn.conn.commit()except Exception as e:dbconn.conn.rollback()logging.exception(e) # 方式2def query(sql):print sqldbconn.cursor.execute(sql);return dbconn.cursordef dbclose():dbconn.cursor.close()dbconn.conn.close()

總結

以上是生活随笔為你收集整理的python连接postgresql数据库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。