1. 程式人生 > >關於python操作mysql和postgresql資料庫的sql 分頁限制語句sql語法問題

關於python操作mysql和postgresql資料庫的sql 分頁限制語句sql語法問題

@本人使用django開發一個數據庫的管理模組,主要開發兩種資料庫的管理,遇到了一些坑

Python 使用psycopg2操作postgresql ,使用pymysql連線mysql

psycopg2 下載

pip install psycopg2

pymysql 下載

pip install pymysql

python 操作mysql 的連線方式

#!/usr/bin/python3
import pymysql
#開啟資料庫連線
db = pymysql.connect(“localhost”,“testuser”,“test123”,“TESTDB” )
#使用 cursor() 方法建立一個遊標物件 cursor
cursor = db.cursor()
#使用 execute() 方法執行 SQL 查詢
cursor.execute(“SELECT VERSION()”)
#使用 fetchone() 方法獲取單條資料.
data = cursor.fetchone()
print ("Database version : %s " % data)
#關閉資料庫連線
db.close()

python 操作postgresql 的連線方式

import psycopg2
#資料庫連線引數
conn = psycopg2.connect(database=“test1”, user=“jm”, password=“123”, host=“127.0.0.1”, port=“5432”)
cur = conn.cursor()
cur.execute(“SELECT * FROM a1;”)
rows = cur.fetchall() # all rows in table
print(rows)
conn.commit()
cur.close()
conn.close()

下面是postgresql分頁過程中的一個sql這個是

下面是msyql分頁過程中的一個sql這個是
在這裡插入圖片描述
之前用psycopg2 對postgresql分頁sql的limit並沒有問題和pymysql一樣

突然程式碼出錯無法分頁 查詢半天postgresql 中

select * fromtest limit 0,25
在這裡插入圖片描述
後來查尋發現要在數字間0,25換成如下,就與 limit 0,25 效果一樣了
select * fromtest limit 25 OFFSET 0

成功執行,由於好長時間下功能都正常,導致自己找了很久的問題還算是解決了。

貼上我sql 語句佔位符的三種總結:

1.直接佔位符拼接sql

   sql = "select * from %s limit %s,25"%(tbname, Start_page) 
   cur.execute(sql)	

2.字串拼接

  sql = “select * from ”+tbname+"limit"+'' ''+Start_page+",25"
  cur.execute(sql)	

3.執行sql佔位

  sql = "SELECT u.datname FROM pg_catalog.pg_database u where u.datname='%s'";
  db = cursor.execute(sql, [databaname])

可以直接賦值的sql建議用這種方式 ,各有各的用處,具體看情況,謝謝!