添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

The cursor class Enables Python scripts to use a database session to run PostgreSQL commands. The connection class is what creates cursors.

cursor() method: They are permanently connected to the connection, and all instructions are run in the context of the database session covered by the connection. Cursors generated from the same connection aren’t separated, which means that any alterations made to the database by one cursor are incontinently visible to the others. Cursors made from separate connections can be isolated or not, depending on the insulation position of the connections.

Cursors are not thread-safe, a multithreaded application can construct multiple cursors from a single connection, and each cursor should be used by a single thread.

Create a simple cursor:

in the below code we form a connection to the “Hospital_database” and a cursor is created using connection.cursor() method.

Python3

# forming the connection
conn = psycopg2.connect(
database = "Hospital_database" , user = 'postgres' ,
password = 'pass' , host = '127.0.0.1' , port = '5432'
# Setting auto commit to True
conn.autocommit = True
# Creating a cursor object using the
# cursor() method
cursor = conn.cursor()

Methods in Cursor Class

execute() method:

Prepare a database operation and run it (query or command). Parameters can be provided in the form of a series or a mapping, and they’ll be tied to variables in the operation. Positional (% s) or named (% (name)s) placeholders are used to specify variables.

None is returned by the method.

Syntax: execute(operation[, parameters])

Example:

Python3

executemany() method:

Build a database action (query or command) and run it against all of the parameter tuples or mappings in a sequence of parameters. The function is especially useful for database update instructions because it discards any result set produced by the query.

Syntax executemany(operation, sequence_of_parameters)

Example:

Python3

# executing the sql statement
cursor.executemany( "INSERT INTO classroom VALUES(%s,%s,%s)" ,
values)

fetchall() method:

All (remaining) rows of a query result are fetched and returned as a list of tuples. If there are no more records to fetch, an empty list is returned.

Syntax: cursor.fetchall()

Example:

Python3

fetchone() method:

Returns a single tuple if the next row of a query result set is available, or None if no further data is available.

Syntax: cursor.fetchone()

Example:

Python3

fetchmany() method:

Returns a list of tuples after fetching the next set of rows from a query result. if there are no more rows available, a blank list is returned.

The argument specifies the number of rows to fetch each call. The cursor’s array size specifies the number of rows to be fetched if it is not specified. The procedure should attempt to retrieve as many rows as the size parameter specifies.

Syntax: cursor. fetchmany([size=cursor.arraysize])

Example:

The below example is to fetch the first two rows.

Python3

callproc() method:

Use the name of a stored database procedure to invoke it. Each argument that the procedure expects must have its own entry in the parameter sequence. The call returns a changed duplicate of the input sequence as the result. The input parameters are left alone, while the output parameters maybe get replaced with new values.

Syntax: curor.callproc(procname[, parameters])

mogrify() method:

After the arguments have been bound, a query string is returned. The string returned is the same as what was sent to the database if you used the execute() method or anything similar.

Syntax: cursor.mogrify(operation[, parameters])

Example:

Python3

# cursor.mogrify() to insert multiple values
args = ',' .join(cursor.mogrify( "(%s,%s,%s)" , i).decode( 'utf-8' )
for i in values)

close() method:

used to close the cursor. From this point forth, the cursor will be inoperable; if any operation is performed with the cursor, an InterfaceError will be raised.

Syntax: curor.close()

Let’s see the below example to see the complete working of the cursor object.

A connection is established to the “Employee_db” database. a cursor is created using the conn.cursor() method, select SQL statement is executed by the execute() method and all the rows of the Table are fetched using the fetchall() method.

Python3

# establishing connection
conn = psycopg2.connect(
database = "Employee_db" , user = 'postgres' ,
password = 'root' , host = 'localhost' , port = '5432'
# setting autocommit to True
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
sql = '''SELECT * FROM employee;'''
# executing the sql command
cursor.execute(sql)
# fetching all the rows
results = cursor.fetchall()
print (results)
# committing changes
conn.commit()
# closing connection
conn.close()

Output:

[(1216755, ‘raj’, ‘data analyst’, 1000000, 2, ‘1216755raj’), (1216756, ‘sarah’, ‘App developer’, 60000, 3, ‘1216756sarah’), (1216757, ‘rishi’, ‘web developer’, 60000, 1, ‘1216757rishi’), (1216758, ‘radha’, ‘project analyst’, 70000, 4, ‘1216758radha’), (1216759, ‘gowtam’, ‘ml engineer’, 90000, 5, ‘1216759gowtam’), (1216754, ‘rahul’, ‘web developer’, 70000, 5, ‘1216754rahul’), (191351, ‘divit’, ‘100000.0’, None, None, ‘191351divit’), (191352, ‘rhea’, ‘70000.0’, None, None, ‘191352rhea’)]

Python Psycopg - Connection class
The connection to a PostgreSQL database instance is managed by the connection class. It's more like a container for a database session. The function connect() is used to create connections to the database. The connect() function starts a new database session and returns a connection class instance. We can construct a new cursor to perform any SQL s
Format SQL in Python with Psycopg's Mogrify
Psycopg, the Python PostgreSQL driver, includes a very useful mechanism for formatting SQL in python, which is mogrify. After parameters binding, returns a query string. The string returned is the same as what SQLwas sent to the database if you used the execute() function or anything similar. One may use the same inputs for mogrify() as you would f
Comparing psycopg2 vs psycopg in Python
PostgreSQL is a powerful, open-source relational database management system known for its robustness, extensibility, and standards compliance. It supports a wide range of data types and complex queries, making it suitable for various applications, from small web applications to large enterprise systems. Comparing psycopg2 vs psycopg in PythonFeatur
Python VLC MediaPlayer - Getting Cursor
In this article we will see how we can get the cursor position in the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can cre
Python SQLite - Cursor Object
In this article, we are going to discuss cursor objects in sqlite3 module of Python. Cursor Object It is an object that is used to make the connection for executing SQL queries. It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database. Syntax: cursor_object=connection_object.ex
PyGame Set Mouse Cursor from Bitmap
In this article, we are going to see how to set the mouse cursor from bitmap using the PyGame module in Python. What is PyGame?It is a cross-platform set of Python modules designed for writing video games.It includes computer graphics and sound libraries designed to be used with the Python programming language.It can handle time, video, music, font
PyQt5 QSpinBox - Setting cursor
In this article we will see how we can set the cursor to the spin box, a cursor is an indicator used to show the current position for user interaction on a computer monitor or other display device that will respond to input from a text input or pointing device. In order to do this we use setCursor method Syntax : spin_box.setCursor(cursor) Argument
PyQt5 QSpinBox - Accessing the cursor
In this article we will see how we can get the cursor of the spin box, a cursor is an indicator used to show the current position for user interaction on a computer monitor or other display device that will respond to input from a text input or pointing device. We use setCursor method to set new cursor to it. In order to do this we use cursor metho
PyQt5 QSpinBox - How to unset the cursor
In this article we will see how we can unset the cursor of the spin box, a cursor is an indicator used to show the current position for user interaction on a computer monitor or other display device that will respond to input from a text input or pointing device. We use setCursor method to set new cursor to it. In order to do this we use unsetCurso
Convert PyMongo Cursor to JSON
Prerequisites: MongoDB Python Basics This article is about converting the PyMongo Cursor to JSON. Functions like find() and find_one() returns the Cursor instance. Let's begin: Importing Required Modules: Import the required module using the command: from pymongo import MongoClient from bson.json_util import dumps If MongoDB is already not installe
Convert PyMongo Cursor to Dataframe
Prerequisites: MongoDB Python Basics This article is about converting the PyMongo Cursor to Pandas Dataframe. Functions like find() and find_one() returns the Cursor instance. Let's begin: Importing Required Modules: Import the required module using the command: from pymongo import MongoClient from pandas import DataFrame If MongoDB is already not
PyQt5 QCalendarWidget - Changing Cursor Shape
In this article we will see how we can change the cursor shape for the QCalendarWidget. Cursor is the mouse pointer by default cursor shape i.e cursor look same for both window or calendar although there are a variety of cursor available for calendar, for example, split cursor, size cursor etc. In order to do this we will use setCursor method with
PyQt5 QCalendarWidget - Getting Cursor Shape
In this article we will see how we can get the cursor shape of the QCalendarWidget. Cursor is the mouse pointer by default cursor shape i.e cursor look same for both window or calendar although there are a variety of cursor available for calendar, for example, split cursor, size cursor etc. By default, it has the arrow cursor but can be changed wit
PyQt5 QCalendarWidget - Making Cursor Shape back to normal
In this article we will see how we can reset the cursor shape of the QCalendarWidget. Cursor is the mouse pointer by default cursor shape i.e cursor look same for both window or calendar although there are a variety of cursor available for calendar, for example, split cursor, size cursor etc. By default, it has the arrow cursor but can be changed w
What is a PyMongo Cursor?
MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) that accommodates more data types. What is a Cursor
wxPython - Change Cursor image on StaticText
In this article we will learn how can we change cursor image when cursor hovers over the static text. We can do it by creating a cursor object and using SetCursor() function associated with wx.StaticText class of wxPython. SetCursor() takes wx.Cursor object as a parameter. Syntax: wx.StaticText.SetCursor(cursor) Parameters: Parameter Input Type Des
wxPython - Change Cursor on hover on Button
In this article we will learn that how can we change cursor when it hovers on Button present in frame. We need to follow some steps as followed. Step 1- Create a wx.Image object with image you want to use as cursor image. Step 2- Create a wx.Cursor object and pass wx.Image object above created. Step 3- Set the cursor using SetCursor() function. Syn
How to check if the PyMongo Cursor is Empty?
MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely used for interacting with a MongoDB database as py
wxPython - Change cursor for ToolBar
In this article will learn how can we change the cursor to a custom image cursor when it hovers over the toolbar. To do this we need to follow some steps as follows. Step 1: Create wx.Image object of the image you like. Step 2: Create wx.Cursor object passing image as parameter. Step 3: Set cursor for toolbar using SetCursor() method. Syntax: wx.To
PyQt5 QCommandLinkButton - Setting Default Cursor Back
In this article we will see how we can remove the new cursor and set the original cursor back to the QCommandLinkButton. Assigning cursor means the mouse cursor will assume the new shape when it's over the command link button. Cursor shape is basically cursor icons these are used to classify the actions. It can be set with the help of setCursor met
PyQt5 QCommandLinkButton - Accessing Cursor
In this article we will see how we can get i.e access cursor of the QCommandLinkButton. Assigning cursor means the mouse cursor will assume the new shape when it's over the command link button. Cursor shape is basically cursor icons these are used to classify the actions. It can be set with the help of setCursor method. In order to do this we use c
PyQt5 QCommandLinkButton - Assigning Cursor
In this article we will see how we can set i.e assign cursor to the QCommandLinkButton. Assigning cursor means the mouse cursor will assume the new shape when it's over the command link button. Cursor shape is basically cursor icons these are used to classify the actions. In order to do this we use setCursor method with the command link button obje
PyQt5 QScrollBar – Setting Cursor
In this article we will see how we can set cursor to the QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. Setting cursor means to set special cursor to the scroll bar which is only for the scroll bar only. In or
PyQt5 QScrollBar – Getting Cursor
In this article we will see how we can get cursor of the QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. Setting cursor means to set special cursor to the scroll bar which is only for the scroll bar only, it ca
PyQt5 QScrollBar – Unsetting Cursor
In this article we will see how we can unset the special cursor of the QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. Setting cursor means to set special cursor to the scroll bar which is only for the scroll b
MoviePy – Getting color of a Frame of Video Clip where cursor touch
In this article, we will see how we can get a color of single frame at given time of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can store the specif
PYGLET – Setting Cursor
In this article we will see how we can set special cursor to the window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill
PYGLET – Getting System Mouse Cursor Object
In this article we will see how we can get the system mouse cursor object in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fi
PYGLET – Drawing Mouse Cursor for Window
In this article we will see how we can draw mouse cursor for window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an
PyQtGraph – Getting Cursor of Bar Graph
In this article we will see how we can get cursor of the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !