欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間: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可以很簡(jiǎn)單的建立PostgreSQL 數(shù)據(jù)庫連接,其中最受歡迎的就是psycopg。

1. 安裝psycopg2

Psycopy是針對(duì)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ù)庫會(huì)顯示在右側(cè)窗格中。

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

3.1 不使用配置文件

下面使用 psycopy2.connect()方法連接到postgresql數(shù)據(jù)庫。通過調(diào)用cursor類中的execute()方法對(duì)數(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 使用配置文件

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

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

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

下面的config()函數(shù)會(huì)讀取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)建一個(gè)新的數(shù)據(jù)庫連接。
  • 然后,新建一個(gè)cursor并執(zhí)行SQL語句來獲取 PostgreSQL 數(shù)據(jù)庫版本。
  • 之后,通過調(diào)用游標(biāo)對(duì)象的 fetchone()方法讀取結(jié)果集。
  • 最后,通過調(diào)用cursorconnection對(duì)象的close()方法關(guān)閉與數(shù)據(jù)庫服務(wù)器的通信。

4. DML語句測(cè)試

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)對(duì)象
cur = con.cursor()
# 用cursor中的execute 使用DDL語句創(chuàng)建一個(gè)名為 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ù)只會(huì)必須要提交才能生效
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)對(duì)象
cur = con.cursor()
# 在表中插入一條數(shù)據(jù)
cur.execute("INSERT INTO STUDENT (ADMISSION,NAME,AGE,COURSE,DEPARTMENT) "
            "VALUES (3420, 'John', 18, 'Computer Science', 'ICT')")

# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
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)對(duì)象
cur = con.cursor()
# 更新表中的數(shù)據(jù)
cur.execute("UPDATE student set name = 'joe' WHERE admission = 3420")

# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
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)對(duì)象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("DELETE FROM student WHERE admission = 3420")

# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
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語句測(cè)試

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)對(duì)象
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ù)只會(huì)必須要提交才能生效
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ù)只會(huì)必須要提交才能生效
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • flask框架自定義url轉(zhuǎn)換器操作詳解

    flask框架自定義url轉(zhuǎn)換器操作詳解

    這篇文章主要介紹了flask框架自定義url轉(zhuǎn)換器操作,結(jié)合實(shí)例形式分析了URL轉(zhuǎn)換器的相關(guān)原理、實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下
    2020-01-01
  • python暴力解壓rar加密文件過程詳解

    python暴力解壓rar加密文件過程詳解

    這篇文章主要介紹了python解壓rar加密文件過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • python的命名規(guī)則知識(shí)點(diǎn)總結(jié)

    python的命名規(guī)則知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家分享的是關(guān)于python的命名規(guī)則知識(shí)點(diǎn)總結(jié),有需要的朋友們可以參考下。
    2019-10-10
  • PyQt通過動(dòng)畫實(shí)現(xiàn)平滑滾動(dòng)的QScrollArea

    PyQt通過動(dòng)畫實(shí)現(xiàn)平滑滾動(dòng)的QScrollArea

    這篇文章主要為大家詳細(xì)介紹了PyQt如何使用Qt的動(dòng)畫框架 QPropertyAnimation來實(shí)現(xiàn)平滑滾動(dòng)的QScrollArea,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的可以學(xué)習(xí)一下
    2023-01-01
  • 使用Pandas實(shí)現(xiàn)清洗客戶編碼異常數(shù)據(jù)

    使用Pandas實(shí)現(xiàn)清洗客戶編碼異常數(shù)據(jù)

    在不同行業(yè)中,我們經(jīng)常會(huì)遇到一個(gè)麻煩的問題:數(shù)據(jù)清洗,尤其是當(dāng)我們需要處理客戶編碼異常數(shù)據(jù)時(shí),下面小編就來和大家分享一下常用的解決辦法吧
    2023-07-07
  • 如何將Python列表轉(zhuǎn)換為字符串

    如何將Python列表轉(zhuǎn)換為字符串

    字符串是Python中最常用的數(shù)據(jù)類型,下面這篇文章主要給大家介紹了關(guān)于如何將Python列表轉(zhuǎn)換為字符串的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-03-03
  • Pycharm無法正常安裝第三方庫的幾條應(yīng)對(duì)方法匯總

    Pycharm無法正常安裝第三方庫的幾條應(yīng)對(duì)方法匯總

    在使用pycharm學(xué)習(xí)python的時(shí)候,經(jīng)常需要第三方庫,沒有第三方庫程序就會(huì)報(bào)錯(cuò),下面這篇文章主要給大家介紹了關(guān)于Pycharm無法正常安裝第三方庫的幾條應(yīng)對(duì)方法,需要的朋友可以參考下
    2023-04-04
  • 使用pandas模塊實(shí)現(xiàn)數(shù)據(jù)的標(biāo)準(zhǔn)化操作

    使用pandas模塊實(shí)現(xiàn)數(shù)據(jù)的標(biāo)準(zhǔn)化操作

    這篇文章主要介紹了使用pandas模塊實(shí)現(xiàn)數(shù)據(jù)的標(biāo)準(zhǔn)化操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Win系統(tǒng)PyQt5安裝和使用教程

    Win系統(tǒng)PyQt5安裝和使用教程

    這篇文章主要介紹了Win系統(tǒng)PyQt5安裝和使用教程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Python實(shí)現(xiàn)一個(gè)完整學(xué)生管理系統(tǒng)

    Python實(shí)現(xiàn)一個(gè)完整學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)學(xué)生管理系統(tǒng)(面向?qū)ο蟀妫?,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2023-01-01

最新評(píng)論