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

使用python進(jìn)行PostgreSQL數(shù)據(jù)庫連接全過程

 更新時間:2025年03月04日 11:27:21   作者:零の守墓人  
這篇文章主要介紹了使用python進(jìn)行PostgreSQL數(shù)據(jù)庫連接的相關(guān)資料,包括安裝psycopg2模塊、使用PyCharm進(jìn)行圖形化連接、代碼連接數(shù)據(jù)庫的方法、以及如何執(zhí)行DML和DQL操作,需要的朋友可以參考下

前言

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

1. 安裝psycopg2

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

pip install psycopg2

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

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

在pycharm中選擇Database,點(diǎn)擊左上角的+添加數(shù)據(jù)庫,選擇postgresql:

創(chuàng)建數(shù)據(jù)庫連接后點(diǎn)擊apply,數(shù)據(jù)庫會顯示在右側(cè)窗格中。

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

3.1 不使用配置文件

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

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

  • database: 要連接的數(shù)據(jù)庫名稱
  • user:連接數(shù)據(jù)庫的用戶名
  • password: 連接數(shù)據(jù)庫的密碼
  • host: 數(shù)據(jù)庫端口的地址,一般為 “localhost”,或者主機(jī)的IP地址
  • port: 門戶 默認(rèn)為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()

運(yùn)行結(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()

怎么運(yùn)行的。

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

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)用游標(biā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)用游標(biā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語句更新目標(biāo)字段,使用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)用游標(biā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語句更新目標(biāo)字段,使用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)用游標(biā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語句更新目標(biāo)字段,使用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)用游標(biā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], "\n")

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

結(jié)果查看:

D:\python3\python.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], "\n")

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

結(jié)果查看:

D:\python3\python.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

總結(jié) 

到此這篇關(guān)于使用python進(jìn)行PostgreSQL數(shù)據(jù)庫連接的文章就介紹到這了,更多相關(guān)python連接PostgreSQL數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

朝阳市| 平利县| 青冈县| 甘肃省| 信丰县| 夏河县| 瑞安市| 赤峰市| 东阳市| 古丈县| 正阳县| 洛川县| 通渭县| 盘山县| 黎平县| 慈利县| 开平市| 乐山市| 桓台县| 皋兰县| 建宁县| 黑龙江省| 南宁市| 九龙城区| 台北市| 河南省| 泰顺县| 监利县| 双柏县| 北京市| 金华市| 平潭县| 黄平县| 织金县| 定边县| 屏东县| 淮滨县| 丹东市| 西乌珠穆沁旗| 论坛| 新兴县|