Python Data Access 简明教程
Python PostgreSQL - Cursor Object
psycopg 库的 Cursor 类提供方法以使用 Python 代码在数据库中执行 PostgreSQL 命令。
The Cursor class of the psycopg library provide methods to execute the PostgreSQL commands in the database using python code.
使用它的方法,您可以执行 SQL 语句、从结果集中获取数据、调用过程。
Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures.
你可以使用 Connection 对象/类的 cursor() 方法来创建 Cursor 对象。
You can create Cursor object using the cursor() method of the Connection object/class.
Example
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
Methods
以下是 Cursor 类/对象提供的各种方法。
Following are the various methods provided by the Cursor class/object.
Sr.No |
Method & Description |
1 |
callproc() This method is used to call existing procedures PostgreSQL database. |
2 |
close() This method is used to close the current cursor object. |
3 |
executemany() This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters. |
4 |
execute() This method accepts a MySQL query as a parameter and executes the given query. |
5 |
fetchall() This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones) |
6 |
fetchone() This method fetches the next row in the result of a query and returns it as a tuple. |
7 |
fetchmany() This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. |
Properties
以下为 Cursor 类的属性:
Following are the properties of the Cursor class −
Sr.No |
Property & Description |
1 |
description This is a read only property which returns the list containing the description of columns in a result-set. |
2 |
astrowid This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation. |
3 |
rowcount This returns the number of rows returned/updated in case of SELECT and UPDATE operations. |
4 |
closed This property specifies whether a cursor is closed or not, if so it returns true, else false. |
5 |
connection This returns a reference to the connection object using which this cursor was created. |
6 |
name This property returns the name of the cursor. |
7 |
scrollable This property specifies whether a particular cursor is scrollable. |