Python PostgreSQL – 限制条款
在本文中,我们将看到如何使用Python的pyscopg2 模块在 PostgreSQL 中使用 limit 子句。在 PostgreSQL LIMIT约束查询返回的行数。默认情况下,它用于从顶部显示一些特定数量的行。如果我们想在返回行之前跳过一些行,那么我们在LIMIT子句之后使用OFFSET子句。
Syntax without using OFFSET: SELECT select_list FROM table_name LIMIT no_of_rows;
Syntax with using OFFSET: SELECT select_list FROM table_name LIMIT no_of_rows OFFSET rows_to_skip;
使用的表:
在这里,我们使用产品表进行演示。
现在让我们使用此表中的限制,因为我们将使用 will psycopg2模块连接 PostgreSQL 并在 cursor.execute(query) 对象中执行 SQL 查询。
Syntax: cursor.execute(sql_query);
示例 1:在 Postgres 中使用Python使用限制子句
Python3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="root",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
print("\ndisplaying five rows from top");
sql = '''SELECT * from products LIMIT 5 '''
# Executing the query
cursor.execute(sql)
# Fetching the data
result = cursor.fetchall();
print(result)
# Commit changes in the database
conn.commit()
# Closing the connection
conn.close()
Python3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="root",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
print("displaying four rows after a particular offset");
sql1 = '''SELECT * from products LIMIT 4 OFFSET 5 '''
# Executing the query
cursor.execute(sql1)
# Fetching the data
result1 = cursor.fetchall();
print(result1)
# Commit changes in the database
conn.commit()
# Closing the connection
conn.close()
输出:
示例 2:使用Python在 Postgres 中使用 limit 和 offset 子句
蟒蛇3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="root",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
print("displaying four rows after a particular offset");
sql1 = '''SELECT * from products LIMIT 4 OFFSET 5 '''
# Executing the query
cursor.execute(sql1)
# Fetching the data
result1 = cursor.fetchall();
print(result1)
# Commit changes in the database
conn.commit()
# Closing the connection
conn.close()
输出: