最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python進行PostgreSQL數(shù)據(jù)庫連接的流程步驟

 更新時間:2026年04月03日 09:17:39   作者:2601_94981616  
本文介紹了使用Python連接PostgreSQL數(shù)據(jù)庫的方法,包括使用psycopg2安裝、圖形化連接和代碼連接,還詳細介紹了DML(數(shù)據(jù)操作語言)和DQL(數(shù)據(jù)查詢語言)語句的測試,涵蓋創(chuàng)建表、插入數(shù)據(jù)、更新數(shù)據(jù)、刪除數(shù)據(jù)和查詢數(shù)據(jù)的操作,需要的朋友可以參考下

使用python進行PostgreSQL 數(shù)據(jù)庫連接

PostgreSQL 數(shù)據(jù)庫是最常用的關(guān)系型數(shù)據(jù)庫之一,最吸引人的一點是它作為開源數(shù)據(jù)庫且具有可拓展性,能夠提供豐富的應用。運用python可以很簡單的建立PostgreSQL 數(shù)據(jù)庫連接,其中最受歡迎的就是psycopg。

1. 安裝psycopg2

Psycopy是針對python的Postgres 數(shù)據(jù)庫的適配模塊,安裝psycopg2可以整合python和Postgres 。使用cmd輸入命令進行安裝:

pip install psycopg2

也可以在pycharm中查找psycopg2安裝包:

2. 圖形化連接數(shù)據(jù)庫

在pycharm中選擇Database,點擊左上角的+添加數(shù)據(jù)庫,選擇postgresql:
創(chuàng)建數(shù)據(jù)庫連接后點擊apply,數(shù)據(jù)庫會顯示在右側(cè)窗格中。

3. 代碼連接數(shù)據(jù)庫

3.1 不使用配置文件

下面使用 psycopy2.connect()方法連接到postgresql數(shù)據(jù)庫。通過調(diào)用cursor類中的execute()方法對數(shù)據(jù)庫進行操作。在execute()中用SQL語句創(chuàng)建表。使用commit()將數(shù)據(jù)發(fā)送到數(shù)據(jù)庫服務器,最后使用close()關(guān)閉數(shù)據(jù)庫。commit()能夠?qū)?shù)據(jù)庫進行改變,且不可逆。

connect() 方法的參數(shù)一般包括:

  • database: 要連接的數(shù)據(jù)庫名稱
  • user:連接數(shù)據(jù)庫的用戶名
  • password: 連接數(shù)據(jù)庫的密碼
  • host: 數(shù)據(jù)庫端口的地址,一般為 “localhost”,或者主機的IP地址
  • port: 門戶 默認為5432.
import psycopg2
con = psycopg2.connect(database=“postgres”,
user=“fbase”,
password=“123456”,
host=“192.168.198.152”,
port=“8432”)
print(con)
print(“Database opened successfully”)
cur = con.cursor()
cur.execute(‘SELECT version()')
db_version = cur.fetchone()
print(db_version)
con.close()

運行結(jié)果如下:

3.2 使用配置文件

可以使用配置文件來存儲所有連接參數(shù)。

database.ini文件的內(nèi)容如下:

[postgresql]
host = 192.168.198.152
database = postgres
user = fbase
password = 123456
port = 8432

下面的config()函數(shù)會讀取database.ini文件并返回連接參數(shù)。該config()函數(shù)放置在config.py文件中:

from configparser import ConfigParser


def config(filename='../../resource/database.ini', section='postgresql'):
    # create a parser
    parser = ConfigParser()
    # read config file
    parser.read(filename)

    # get section, default to postgresql
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    return db

下面的connect()函數(shù)連接到suppliers數(shù)據(jù)庫并打印出 PostgreSQL 數(shù)據(jù)庫版本。

import psycopg2

from demo.pgdemo.config import config


def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)

        # create a cursor
        cur = conn.cursor()

        # execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)

        # close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')


if __name__ == '__main__':
    connect()

怎么運行的。

  • 首先,從database.ini文件中讀取數(shù)據(jù)庫連接參數(shù)。
  • 接下來,通過調(diào)用connect()函數(shù)創(chuàng)建一個新的數(shù)據(jù)庫連接。
  • 然后,新建一個cursor并執(zhí)行SQL語句來獲取 PostgreSQL 數(shù)據(jù)庫版本。
  • 之后,通過調(diào)用游標對象的 fetchone()方法讀取結(jié)果集。
  • 最后,通過調(diào)用cursorconnection對象的close()方法關(guān)閉與數(shù)據(jù)庫服務器的通信。

4. DML語句測試

4.1 創(chuàng)建表

使用SQL(Structured Query Language)語句CREATE TABLE添加新的表:

import psycopg2

# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
                       user="fbase",
                       password="123456",
                       host="192.168.198.152",
                       port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 用cursor中的execute 使用DDL語句創(chuàng)建一個名為 STUDENT 的表,指定表的字段以及字段類型
cur.execute('''
       CREATE TABLE IF NOT EXISTS STUDENT
      (ADMISSION INT PRIMARY KEY     NOT NULL,
      NAME           TEXT            NOT NULL,
      AGE            INT             NOT NULL,
      COURSE        CHAR(50),
      DEPARTMENT        CHAR(50));''')

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

postgres=# d
        List of relations
 Schema |  Name   | Type  | Owner 
--------+---------+-------+-------
 public | student | table | fbase
(1 row)

4.2 表插入數(shù)據(jù)

使用INSERT INTO 在以經(jīng)生成的表中插入數(shù)據(jù)

import psycopg2

# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
                       user="fbase",
                       password="123456",
                       host="192.168.198.152",
                       port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 在表中插入一條數(shù)據(jù)
cur.execute("INSERT INTO STUDENT (ADMISSION,NAME,AGE,COURSE,DEPARTMENT) "
            "VALUES (3420, 'John', 18, 'Computer Science', 'ICT')")

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

postgres=# select * from student ;
 admission | name | age |                       course                       |                     department                     
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
      3420 | John |  18 | Computer Science                                   | ICT                                               
(1 row)

4.3 表更新數(shù)據(jù)

同樣使用SQL語句更新目標字段,使用commit()更新數(shù)據(jù)庫

import psycopg2

# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
                       user="fbase",
                       password="123456",
                       host="192.168.198.152",
                       port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 更新表中的數(shù)據(jù)
cur.execute("UPDATE student set name = 'joe' WHERE admission = 3420")

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

postgres=# select * from student ;
 admission | name | age |                       course                       |                     department                     
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
      3420 | John |  18 | Computer Science                                   | ICT                                               
(1 row)
postgres=# select * from student ;
 admission | name | age |                       course                       |                     department                     
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
      3420 | joe  |  18 | Computer Science                                   | ICT                                        
(1 row)

4.4 表刪除數(shù)據(jù)

同樣使用SQL語句更新目標字段,使用commit()更新數(shù)據(jù)庫

import psycopg2

# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
                       user="fbase",
                       password="123456",
                       host="192.168.198.152",
                       port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("DELETE FROM student WHERE admission = 3420")

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

postgres=# select * from student ;
 admission | name | age |                       course                       |                     department                     
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
      3420 | joe  |  18 | Computer Science                                   | ICT                                               
(1 row)
postgres=# select * from student ;
 admission | name | age | course | department 
-----------+------+-----+--------+------------
(0 rows)

5. DQL語句測試

5.1 查看表中的數(shù)據(jù)

同樣使用SQL語句更新目標字段,使用commit()更新數(shù)據(jù)庫

import psycopg2

# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
                       user="fbase",
                       password="123456",
                       host="192.168.198.152",
                       port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("SELECT * FROM student")

rows = cur.fetchall()
for row in rows:
    print("ADMISSION =", row[0])
    print("NAME =", row[1])
    print("AGE =", row[2])
    print("COURSE =", row[3])
    print("DEPARTMENT =", row[4], "
")

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

D:python3python.exe D:/project/python/demo/demo/pgdemo/dql_select_1.py
Database opened successfully
ADMISSION = 3420
NAME = John
AGE = 18
COURSE = Computer Science                                  
DEPARTMENT = ICT
w[3])
    print("DEPARTMENT =", row[4], "
")

# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()

結(jié)果查看:

D:python3python.exe D:/project/python/demo/demo/pgdemo/dql_select_1.py
Database opened successfully
ADMISSION = 3420
NAME = John
AGE = 18
COURSE = Computer Science                                  
DEPARTMENT = ICT

以上就是使用Python進行PostgreSQL數(shù)據(jù)庫連接的流程步驟的詳細內(nèi)容,更多關(guān)于Python連接PostgreSQL數(shù)據(jù)庫的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 一小時學會TensorFlow2之Fashion Mnist

    一小時學會TensorFlow2之Fashion Mnist

    這篇文章主要介紹了TensorFlow2之Fashion Mnist,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • 使用Python實現(xiàn)不同需求的排行榜功能

    使用Python實現(xiàn)不同需求的排行榜功能

    這篇文章主要為大家介紹了Python實現(xiàn)不同需求的排行榜功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Python基礎(chǔ)之數(shù)據(jù)結(jié)構(gòu)詳解

    Python基礎(chǔ)之數(shù)據(jù)結(jié)構(gòu)詳解

    這篇文章主要介紹了Python基礎(chǔ)之數(shù)據(jù)結(jié)構(gòu)詳解,文中有非常詳細的代碼示例,對正在學習python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • Python讀取圖像并顯示灰度圖的實現(xiàn)

    Python讀取圖像并顯示灰度圖的實現(xiàn)

    這篇文章主要介紹了Python讀取圖像并顯示灰度圖的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • Python實現(xiàn)讀取Excel表數(shù)據(jù)并轉(zhuǎn)為JSON格式文件

    Python實現(xiàn)讀取Excel表數(shù)據(jù)并轉(zhuǎn)為JSON格式文件

    這篇文章主要為大家詳細介紹了Python如何使用pandas庫讀取Excel表并將其轉(zhuǎn)為JSON格式文件,文中的示例代碼講解詳細,感興趣的小伙伴可以參考下
    2025-04-04
  • python K近鄰算法的kd樹實現(xiàn)

    python K近鄰算法的kd樹實現(xiàn)

    這篇文章主要介紹了python K近鄰算法的kd樹實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-09-09
  • Python實現(xiàn)快捷啟動本地應用

    Python實現(xiàn)快捷啟動本地應用

    這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)一個快捷啟動器,可以實現(xiàn)快速啟動本地應用和文件秒開,感興趣的小伙伴可以跟隨小編一起學習一下
    2025-07-07
  • Python 機器學習第一章環(huán)境配置圖解流程

    Python 機器學習第一章環(huán)境配置圖解流程

    機器學習是一類算法的總稱,這些算法企圖從大量歷史數(shù)據(jù)中挖掘出其中隱含的規(guī)律,并用于預測或者分類,更具體的說,機器學習可以看作是尋找一個函數(shù),輸入是樣本數(shù)據(jù),輸出是期望的結(jié)果,只是這個函數(shù)過于復雜,以至于不太方便形式化表達
    2021-11-11
  • 從安裝到精通詳解Python包管理神器pip完全指南(小白友好版)

    從安裝到精通詳解Python包管理神器pip完全指南(小白友好版)

    本文是一篇Python包管理工具pip的全面指南,從基礎(chǔ)到進階介紹了pip的核心功能和使用技巧,全文采用通俗易懂的語言,適合Python初學者,快跟隨小編一起學習一下吧
    2026-03-03
  • Python實現(xiàn)對Excel表格的操作詳解

    Python實現(xiàn)對Excel表格的操作詳解

    這篇文章主要介紹了Python實現(xiàn)對Excel表格的操作,在數(shù)據(jù)處理和報告生成等工作中,Excel表格是一種常見且廣泛使用的工具,使用Python來處理Excel表格能夠大大的提升效率,感興趣的同學可以參考下
    2024-02-02

最新評論

邢台县| 通州区| 石阡县| 邢台市| 仙桃市| 平度市| 筠连县| 五指山市| 桐城市| 巍山| 昌吉市| 文昌市| 平顶山市| 新津县| 阜康市| 军事| 清苑县| 藁城市| 大英县| 隆安县| 曲靖市| 西安市| 多伦县| 柏乡县| 嵩明县| 赤峰市| 中西区| 延川县| 枝江市| 丰原市| 横峰县| 怀集县| 新津县| 富顺县| 宜章县| 唐山市| 辽阳县| 江津市| 吉安县| 峨眉山市| 股票|