使用python操作postgresql 查询
1 安裝 psycopg2
pip install psycopg22、連接數(shù)據(jù)庫(kù)
每條完整的sql執(zhí)行步驟如下;
輸出結(jié)果打印出數(shù)據(jù)庫(kù)版本說(shuō)明連接數(shù)據(jù)庫(kù)成功:
database version : PostgreSQL 11.3, compiled by Visual C++ build 1914, 64-bit
三 創(chuàng)建表
創(chuàng)建學(xué)生表主要有字段id?唯一標(biāo)識(shí),字段?num?代表學(xué)號(hào),字段?name?代表學(xué)生姓名;詳細(xì)的建表默認(rèn)規(guī)則轉(zhuǎn)換見(jiàn)附錄
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql = """CREATE TABLE student ( id serial4 PRIMARY KEY, num int4, name varchar(25));""" # 執(zhí)行語(yǔ)句 cursor.execute(sql) print("student table created successfully") # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()四 插入操作
4.1 插入數(shù)據(jù)一
知識(shí)追尋者提供的第一種防止sql注入的插入數(shù)據(jù)方式(具有占位符的預(yù)編譯sql),重要程度不言而喻;美中不足是字符串類(lèi)型必須帶上單引號(hào);
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="INSERT INTO student (num, name) \VALUES (%s, '%s')" % \(100, 'zszxz') # 執(zhí)行語(yǔ)句 cursor.execute(sql) print("successfully") # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()4.2 插入數(shù)據(jù)二(參數(shù)分離)
知識(shí)追尋者認(rèn)為下面參數(shù)與sql語(yǔ)句分離插入的姿勢(shì)更簡(jiǎn)便帥氣,也是防止sql注入問(wèn)題;強(qiáng)烈推薦;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""INSERT INTO student (num, name) VALUES (%s, %s)""" params = (101, 'zszxz') # 執(zhí)行語(yǔ)句 cursor.execute(sql,params) print("successfully") # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()4.3 插入數(shù)據(jù)三(字典)
第三種姿勢(shì)也就是是支持字典映射關(guān)系插入,使用字典方式的插入數(shù)據(jù)是根據(jù)字典的key進(jìn)行匹配占位符,強(qiáng)烈推薦;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""INSERT INTO student (num, name) VALUES (%(num)s, %(name)s)""" params = {'num':102, 'name':'zszxz'} # 執(zhí)行語(yǔ)句 cursor.execute(sql,params) print("successfully") # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()五 查詢(xún)操作
5.1 查詢(xún)一條數(shù)據(jù)
使用fetchone()方法可以抓取一條數(shù)據(jù), 返回的是元組;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""SELECT * FROM student;""" # 執(zhí)行語(yǔ)句 cursor.execute(sql) # 抓取 row = cursor.fetchone() print(row) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()輸出結(jié)果:
(1, 100, 'zszxz')5.2 查詢(xún)多條數(shù)據(jù)
輸出結(jié)果:
[(1, 100, 'zszxz'), (2, 101, 'zszxz')]5.3 查詢(xún)?nèi)繑?shù)據(jù)
使用?fetchall()?方法會(huì)抓取所有數(shù)據(jù);
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""SELECT * FROM student;""" # 執(zhí)行語(yǔ)句 cursor.execute(sql) # 抓取 rows = cursor.fetchall() print(rows) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()輸出結(jié)果:
[(1, 100, 'zszxz'), (2, 101, 'zszxz'), (3, 102, 'zszxz')]5.4 按條件查詢(xún)
輸出結(jié)果:
[(1, 100, 'zszxz')]六 更新操作
更新操作跟之前的查詢(xún),插入類(lèi)似,參數(shù)對(duì)應(yīng)的文章分清楚即可。
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""update student set name = %s where id = %s """ params = ('知識(shí)追尋者',3,) # 執(zhí)行語(yǔ)句 cursor.execute(sql,params) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()七 刪除操作
刪除操作很簡(jiǎn)單,看如下代碼,與之前的代碼流程沒(méi)什么區(qū)別;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""delete from student where id = %s """ params = (3,) # 執(zhí)行語(yǔ)句 cursor.execute(sql,params) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()八 異常處理
處理 sql 的異常非常重要,知識(shí)追尋者這邊使用psycopg2的?Error?進(jìn)行異常捕獲,能捕獲到sql執(zhí)行時(shí)期的所有異常;下面代碼中表test是庫(kù)中不存的表,執(zhí)行sql后會(huì)報(bào)異常,經(jīng)過(guò)異常捕獲后非常美觀,不影響程序運(yùn)行;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""select * from test""" params = (3,) try:# 執(zhí)行語(yǔ)句cursor.execute(sql,params) except psycopg2.Error as e:print(e) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()執(zhí)行結(jié)果
錯(cuò)誤: 關(guān)系 "test" 不存在 LINE 1: select * from test九 打印sql
使用cursor.query?可以查看執(zhí)行的sql語(yǔ)句,方便排查;
# -*- coding: utf-8 -*- import psycopg2 # 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""select * from student""" try:# 執(zhí)行語(yǔ)句cursor.execute(sql,)que = cursor.queryprint(que) except psycopg2.Error as e:print(e) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 cursor.close() conn.close()執(zhí)行結(jié)果:
b'select * from student'十 獲取總條數(shù)
使用cursor.rowcount 可以獲得表中所有行總數(shù);
# 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""select * from student""" # 執(zhí)行語(yǔ)句 cursor.execute(sql) count = cursor.rowcount print(count) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()輸出
2十一顯示行號(hào)
使用cursor.rownumber 可以顯示當(dāng)前查詢(xún)sql獲得數(shù)據(jù)的行號(hào),每抓取一次光標(biāo)的索引就會(huì)加1;
# 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""select * from student """ # 執(zhí)行語(yǔ)句 cursor.execute(sql) row_1 = cursor.fetchone() print(cursor.rownumber) row_2 = cursor.fetchone() print(cursor.rownumber) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()輸出結(jié)果:
1 2十二 顯示執(zhí)行參數(shù)
使用?mogrify(operation[,?parameters]) 能夠顯示執(zhí)行語(yǔ)句的參數(shù)綁定結(jié)果,返回的是字符串形式;
# 獲得連接 conn = psycopg2.connect(database="python", user="postgres", password="123456", host="127.0.0.1", port="5432") # 獲得游標(biāo)對(duì)象,一個(gè)游標(biāo)對(duì)象可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行操作 cursor = conn.cursor() # sql語(yǔ)句 建表 sql ="""INSERT INTO student (num, name) VALUES (%s, %s)""" params = (102, '知識(shí)追尋者') # 執(zhí)行語(yǔ)句 result = cursor.mogrify(sql,params) print(result.decode('UTF-8')) cursor.execute(sql,params) # 事物提交 conn.commit() # 關(guān)閉數(shù)據(jù)庫(kù)連接 conn.close()執(zhí)行結(jié)果:
INSERT INTO student (num, name) VALUES (102, '知識(shí)追尋者')十三 附錄
支持默認(rèn)的類(lèi)型轉(zhuǎn)換如下,如果想要使用強(qiáng)制類(lèi)型轉(zhuǎn)換,詳細(xì)的可以參照pgsql官網(wǎng)手冊(cè);
| None | NULL |
| bool | bool |
| float | real,double |
| int,long | smallint,integer,bigint |
| Decimal | numeric |
| str,unicode | varchar,text |
| buffer,memoryview,bytearray,bytes,Buffer protocol | bytea |
| date | date |
| time | time,timetz |
| datetime | timestamp,timestamptz |
| timedelta | interval |
| list | ARRAY |
| tuple,namedtuple | Composite typesIN?syntax |
| dict | hstore |
| Range | range |
| UUID | uuid |
| Anything | json |
| ipaddress | inet |
?
?
?
總結(jié)
以上是生活随笔為你收集整理的使用python操作postgresql 查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python面向对象---类的基本使用
- 下一篇: python – 处理psycopg2中