亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python模塊psycopg2連接postgresql的實現(xiàn)

 更新時間:2023年07月31日 10:13:56   作者:〖羊頭〗? lsy  
本文主要介紹了Python模塊psycopg2連接postgresql的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

1. 基礎語法

語法

psycopg2.connect(
    dsn         #指定連接參數(shù)??梢允褂脜?shù)形式或 DSN 形式指定。
    host        #指定連接數(shù)據(jù)庫的主機名。
    dbname      #指定數(shù)據(jù)庫名。
    user        #指定連接數(shù)據(jù)庫使用的用戶名。
    password    #指定連接數(shù)據(jù)庫使用的密碼。
    port        #指定連接數(shù)據(jù)庫的端口號。
    connection_factory  #指定創(chuàng)建連接對象的工廠類。
    cursor_factory      #指定創(chuàng)建游標對象的工廠類。
    async_      #指定是否異步連接(默認False)。
    sslmode     #指定 SSL 模式。
    sslrootcert #指定證書文件名。
    sslkey      #指定私鑰文件名。
    sslcert     #指定公鑰文件名。
)

2. 基礎用法

import psycopg2
# 連接數(shù)據(jù)庫
conn_pg = psycopg2.connect("host=localhost dbname=test user=postgres password=123456 port=5432")
# 創(chuàng)建一個游標
cur = conn_pg.cursor()
# 執(zhí)行SQL語句
cur.execute("select * from t1 limit 10;")
# 獲取返回的結果
rows = cur.fetchall()
# 遍歷每行結果(也可以直接打印,輸出格式為列表)
for i in rows:
    print(i)
# 關閉游標
cur.close()
# 關閉連接
conn_pg.close()

結果如下

3. 多條SQL

多條SQL語句直接放入 execute 方法中即可

import psycopg2
# 編寫要執(zhí)行的SQL語句
sql_statements = """
    SELECT * FROM t1 WHERE c1 = 1;
    UPDATE t1 SET c2 = 'yt' WHERE c1 = 1;
    SELECT * FROM t1 WHERE c1 = 1;
"""
# 連接數(shù)據(jù)庫
with  psycopg2.connect("host=localhost dbname=test user=postgres password=123456 port=5432") as conn_pg:
    with conn_pg.cursor() as cur:
        # 執(zhí)行SQL語句
        cur.execute(sql_statements)
        # 獲取返回的結果
        rows = cur.fetchall()
        # 輸出結果
        print(rows)
        # 提交事務
        conn_pg.commit()

這種方法只返回最后一條SQL語句的結果,如果需要全部返回,使用遍歷的方法逐條發(fā)送即可

4. 事務SQL

#!/usr/bin/python
import psycopg2
# 連接數(shù)據(jù)庫
with  psycopg2.connect("host=localhost dbname=test user=postgres password=123456 port=5432") as conn_pg:
    with conn_pg.cursor() as cur:
        try:
            cur.execute("BEGIN") #開始事務
            cur.execute("INSERT INTO t1 VALUES (1, 'abc');")
            cur.execute("UPDATE t1 SET c2 = 'def' WHERE c1 = 1;")
            conn_pg.commit()     #提交事務
        except:
            conn.rollback()      #回滾事務

到此這篇關于Python模塊psycopg2連接postgresql的實現(xiàn)的文章就介紹到這了,更多相關Python連接postgresql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論