关于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建议用这种方式 ,各有各的用处,具体看情况,谢谢!

猜你喜欢

转载自blog.csdn.net/weixin_43178103/article/details/83147748