Python執(zhí)行PostgreSQL數(shù)據(jù)庫的SQL腳本詳解
使用psycopg2插件
psycopg2插件簡(jiǎn)介
psycopg2庫介紹: Psycopg2是一個(gè)用于Python編程語言的第三方庫,用于訪問PostgreSQL數(shù)據(jù)庫系統(tǒng)。它提供了一組工具和方法,可以輕松地在Python程序中進(jìn)行數(shù)據(jù)庫操作,包括查詢、插入、更新、刪除等操作。
以下是Psycopg2庫的一些主要特點(diǎn):
1.簡(jiǎn)單易用:Psycopg2提供了簡(jiǎn)單的API,易于學(xué)習(xí)和使用。
2.高性能:Psycopg2是基于C語言實(shí)現(xiàn)的,能夠提供高效的數(shù)據(jù)庫操作。
3.完全兼容:Psycopg2與PostgreSQL數(shù)據(jù)庫完全兼容,并支持大多數(shù)PostgreSQL特性。
4.安全性:Psycopg2具有內(nèi)置的防止SQL注入攻擊的功能,能夠保證數(shù)據(jù)安全。
5.使用Psycopg2庫進(jìn)行數(shù)據(jù)庫操作通常需要以下步驟:
- 安裝psycopg2庫:可以使用pip install psycopg2來安裝該庫。
- 建立數(shù)據(jù)庫連接:使用psycopg2庫提供的connect()方法建立與數(shù)據(jù)庫的連接。
- 執(zhí)行SQL語句:使用psycopg2提供的方法執(zhí)行SQL語句,如查詢、插入、更新等操作。
- 處理查詢結(jié)果:如果執(zhí)行的是查詢操作,需要使用fetchone()或fetchall()方法來處理查詢結(jié)果。
- 關(guān)閉連接:最后需要使用close()方法關(guān)閉數(shù)據(jù)庫連接。
psycopg2插件使用
1、Python更新pip插件
以管理員權(quán)限打開命令行窗口,執(zhí)行下面的命令:
python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple

2、Python安裝psycopg2插件
以管理員權(quán)限打開命令行窗口,執(zhí)行下面的命令:
pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple

報(bào)錯(cuò):ERROR: Cannot determine archive format of C:\Users\tttzz\AppData\Local\Temp\pip-req-build-rrzp7n41
3、信任該安裝源
以管理員權(quán)限打開命令行窗口,執(zhí)行下面的命令:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn psycopg2

1.4、Python安裝chardet插件
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn chardet

PyCharm下安裝chardet插件,安裝完畢。
5、查看已安裝的插件pip list
pip list

從上面的清單,發(fā)現(xiàn)插件chardet及psycopg2都安裝成功了,下面開始來創(chuàng)建Python文件來對(duì)PostgreSQL數(shù)據(jù)庫進(jìn)行操作。
6、創(chuàng)建Python文件
PostgreSQLExecuteSql.py
上代碼:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import chardet
import psycopg2
import psycopg2.extras
class PostgreSQLExecuteSql:
"""
Python Test Library for TZQ
"""
def __init__(self):
pass
def get_encoding(self, file):
# 獲取文件編碼類型
# 二進(jìn)制方式讀取,獲取字節(jié)數(shù)據(jù),檢測(cè)類型
with open(file, 'rb') as f:
return chardet.detect(f.read())['encoding']
# 輸出文件所有內(nèi)容
def get_file_content1(self, file_path):
# filePath="d:/20220711-1657.sql"
file_encoding = self.get_encoding(file_path)
# print(get_encoding(filePath))
file = open(file_path, "r", encoding=file_encoding)
# print(file.read())
str = file.read()
file.close()
return str
# 按行輸出文件內(nèi)容
def get_file_content2(self, filePath):
# filePath="d:/20220711-1657.sql"
file_encoding = self.get_encoding(filePath)
print(self.get_encoding(filePath))
file = open(filePath, "r", encoding=file_encoding)
# print(file.readline())
str = file.readline()
file.close()
return str
# for循環(huán)讀取文件內(nèi)容
def get_file_content3(self, filePath):
with open(filePath, "r", encoding=self.get_encoding(filePath)) as file:
for item in file:
print("file_content:" + item)
# conn = psycopg2.connect("dbname=tzqlog_pro user=tzq password=Tzq@123456 host=127.0.0.1 port=5432")
# 連接數(shù)據(jù)庫執(zhí)行腳本
def conn_db_exec_sql(self, sql_script, dbname, user, password, host, port):
connect_string = "dbname=" + dbname + " user=" + user + " password=" + password + " host=" + host + " port=" + port
print(connect_string)
# 連接到數(shù)據(jù)庫
conn = psycopg2.connect(connect_string)
# 建立游標(biāo),用來執(zhí)行數(shù)據(jù)庫操作
# 這?創(chuàng)建的是?個(gè)字典Cursor, 這樣返回的數(shù)據(jù), 都是字典的形式, ?便使?
# cursor = conn.cursor()
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# 讀取文本文件中的內(nèi)容
file_content = self.get_file_content1(sql_script)
# 執(zhí)行SQL命令
cursor.execute(file_content)
# 提交SQL命令
conn.commit()
# 執(zhí)行SQL SELECT命令
# command = 'SELECT * FROM test_conn '
# cursor.execute(command)
## 獲取SELECT返回的元組
# rows = cursor.fetchall()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
# print(rows)
"""TZQLOG"""
# 連接數(shù)據(jù)庫執(zhí)行腳本 - TZQLOG PRO 環(huán)境
def exec_sql__TZQLOG_DB_PRO(self, sql_script):
# 配置項(xiàng)
dbname = "tzqlog_db_pro"
user = "plan"
password = "Tzq@123456"
host = "127.0.0.1"
port = "5432"
self.conn_db_exec_sql(sql_script, dbname, user, password, host, port)
# if __name__ == '__main__':
# postgreSQLExecuteSql = PostgreSQLExecuteSql()
# # 執(zhí)行的腳本文件全路徑
# sql_file_path = "D:/20220706-1736-tzqlog_XXX.sql"
# # 在 TZQLOG PRO 執(zhí)行腳本
# postgreSQLExecuteSql.exec_sql__TZQLOG_DB_PRO(sql_file_path)
7、創(chuàng)建Python文件
execute_db_script.py
上代碼:
#!/usr/bin/python # -*- coding: UTF-8 -*- import PostgreSQLExecuteSql # from PostgreSQLExecuteSql import PostgreSQLExecuteSql # import sys ''' TZQ 環(huán)境 匯總 一套執(zhí)行 ''' # 執(zhí)行的腳本文件全路徑 # 腳本目錄名 DIR_STRING = "D:/oracle_database/sql/" # 腳本文件名 # FILE_NAME = "20220706-1736-tzq-xxxxx.sql" # FILE_NAME = "20220715-1522-張三-xxxx更新.sql" FILE_NAME = "20230822-2312-log創(chuàng)建表-log_test_t.sql" ''' TZQ 環(huán)境 匯總 一套執(zhí)行 ''' # 腳本全路徑 sql_file_path = DIR_STRING + FILE_NAME print(sql_file_path) # 定義類的實(shí)例 postgreSQLExecuteSql = PostgreSQLExecuteSql.PostgreSQLExecuteSql() # ################################各個(gè)環(huán)境下執(zhí)行腳本################################ # 在 “TZQ DEV 環(huán)境” 執(zhí)行腳本 # postgreSQLExecuteSql.exec_sql__TZQLOG_DB_DEV(sql_file_path) # 在 “TZQ PRO 環(huán)境” 執(zhí)行腳本 postgreSQLExecuteSql.exec_sql__TZQLOG_DB_PRO(sql_file_path)
8、創(chuàng)建測(cè)試SQL腳本
20230822-2312-log創(chuàng)建表-log_test_t.sql
在 D:/oracle_database/sql/ 目錄下創(chuàng)建腳本文件:20230822-2312-log創(chuàng)建表-log_test_t.sql:
create table log_info_t ( info_id INT8 not null, info_type_id INT8, title VARCHAR(200), content TEXT, article_view_count INT8 default 1 not null, created_by INT8 default -1 not null, creation_date TIMESTAMP(0) default CURRENT_TIMESTAMP not null, last_updated_by INT8 default -1 not null, last_update_date TIMESTAMP(0) default CURRENT_TIMESTAMP not null, delete_flag VARCHAR(1) default 'N' not null, deleted_by INT8, delete_date TIMESTAMP(0), content_no_html TEXT, info_right VARCHAR(50) default 'all' ); CREATE SEQUENCE log_info_s;
如下圖:

腳本內(nèi)容是創(chuàng)建表和序列。下面我們來執(zhí)行下Python腳本,看能不能在我們的目標(biāo)數(shù)據(jù)庫中能夠創(chuàng)建表和序列。
9、執(zhí)行execute_db_script.py
執(zhí)行完后信息:

10、查看數(shù)據(jù)庫
查看數(shù)據(jù)庫中,已經(jīng)有了這個(gè)表和序列

至此。Python執(zhí)行PostgreSQL數(shù)據(jù)庫的SQL腳本,就為大家演示完畢了!!!
以上就是Python執(zhí)行PostgreSQL數(shù)據(jù)庫的SQL腳本詳解的詳細(xì)內(nèi)容,更多關(guān)于Python執(zhí)行PostgreSQL數(shù)據(jù)庫sql腳本的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決pip安裝報(bào)錯(cuò)required?to?install?pyproject.toml-based?projec
這篇文章主要介紹了解決pip安裝報(bào)錯(cuò)required?to?install?pyproject.toml-based?projects問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Python中的字符串類型基本知識(shí)學(xué)習(xí)教程
這篇文章主要介紹了Python中的字符串類型基本知識(shí)學(xué)習(xí)教程,包括轉(zhuǎn)義符和字符串拼接以及原始字符串等基礎(chǔ)知識(shí)講解,需要的朋友可以參考下2016-02-02
python區(qū)塊鏈基本原型簡(jiǎn)版實(shí)現(xiàn)示例
這篇文章主要為大家介紹了python區(qū)塊鏈基本原型簡(jiǎn)版實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python通過ftplib登錄到ftp服務(wù)器的方法
這篇文章主要介紹了python通過ftplib登錄到ftp服務(wù)器的方法,涉及Python使用ftplib模塊的相關(guān)技巧,需要的朋友可以參考下2015-05-05
Python使用urllib2獲取網(wǎng)絡(luò)資源實(shí)例講解
urllib2是Python的一個(gè)獲取URLs(Uniform Resource Locators)的組件。他以u(píng)rlopen函數(shù)的形式提供了一個(gè)非常簡(jiǎn)單的接口,下面我們用實(shí)例講解他的使用方法2013-12-12
Python程序包的構(gòu)建和發(fā)布過程示例詳解
Python程序包的構(gòu)建和發(fā)布過程,本文通過示例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-06-06

