×

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution techniques and how to use them in Python will be covered in this tutorial.

Through MySQL, we may build the cursor object.

Build the cursor object:

code:

#python py_mysql.py


#the library be imported
import mysql.connector


# generating connection
con = mysql.connector.connect(
  host="localhost",
  user="Annu",
  password="Password"
)
#print out the connection
print(con)
# from the connection, import the cursor (con)


my_cursor = con.cursor()
#print out the my_cursor
print (my_cursor)

output:

<mysql.connector.connection.MySQLConnection object at 0x000001B379405CF0>
MySQLCursor: (Nothing executed yet)

Line 4: From MySQL, we import the connector class.

Lines 7 to 11: We use the connector class, which we have imported into our program, to access the connect method. We are currently supplying the connect method with our connection parameters. Depending on how you installed things, a separate username, as well as a password, will apply.

Line 16: We generated the cursor object and imported the cursor function from the connection (con) object (my_cursor).

Line 18: my_cursor, which we generated on line 16, is now printed in line 18, and the output reveals that MySQLCursor: (Nothing executed yet).

Function cursor.execute():

The execute () technique helps us to run the query and have the results match the query. The execute () function's syntax is as follows:

execute (query, args = None)

Parameters:

  • Query: This ought to be a strings type.
  • Arguments: By default, there are no arguments given because there are occasions when we can supply merely a query, such as a SELECT query that retrieves records without asking for any values. So that's the explanation behind the default value of args=None. However, the type of argument for an INSERT query must only be a tuple, list, or dict if we want to pass values.

Returns:

  • The total number of rows impacted by the query will be returned.

Returned By:

  • An integer will be the return type (int).
  • We will now provide some samples.

Example 1: Only use the execute () function for queries.

# python py_mysql.py


# the library be imported
import mysql.connector


# generating connection
con = mysql.connector.connect (
  host="localhost",
  user="Annu",
  password="Password",
  database ="db_test"
)


# from the connection, import the cursor (con)
my_cursor = con.cursor()


my_cursor.execute ("SELECT * FROM STUDENT")


# iterate the outcome
for row in my_cursor:
    print (row)


# Closing the con and cursor
my_cursor.close ()
con.close ()

Output:

(1, 'Amit', 'IT')
(2, 'Anshu', 'Commerce')
(3, 'Sonali', 'Science')
(4, 'Rohit', 'Commerce')
(5, 'Arpit', 'IT')
(6, 'Reyansh', 'Science')

Line 11: We expanded the database by one additional parameter name. Now, just this MySql database (db_test) will be attempted to connect to by our Python code.

Line 15: A cursor object was made (my_cursor).

Line 17: Using the execute function, we run the straightforward SELECT query.

Lines 20 to 21: As we iterated through the outcomes returned by the cursor object, we found that each record was returned as a tuple.

Example 2: For single record insertion, use the execute () function.

# python py_mysql.py


# the library be imported
import mysql.connector


# establishing a database connection
con = mysql.connector.connect(
  host="localhost",
  user="Annu",
  password="Password",
  database="db_test"
)


my_cursor = con.cursor()


# run the query using the value of their record.
query = 'INSERT INTO STUDENT (rollNo, Name, Subject) VALUES (%s, %s, %s)'
value = (8, "Ripunj", "Arts")




my_cursor.execute(query,value)


#We store the data in a table.
con.commit()


print (my_cursor.rowcount, "record(s) inserted.")

Output:

1 record(s) inserted.

Now, see the data in the table

mysql> select * from student;
+--------+---------+----------+
| rollNo | Name    | Subject  |
+--------+---------+----------+
|      1 | Amit    | IT       |
|      2 | Anshu   | Commerce |
|      3 | Sonali  | Science  |
|      4 | Rohit   | Commerce |
|      5 | Arpit   | IT       |
|      6 | Reyansh | Science  |
|      7 | Ripunj  | Arts     |
+--------+---------+----------+
7 rows in set (0.00 sec)


mysql>

Line 11: We expanded the database by one additional parameter name. Now, just this MySql database (db_test) will be attempted to connect to by our Python code.

Line 17: We formulate our insertion data query.

Line 18: To insert the value for such query into the table, we create it.

Line 21: We call the execute () method and provide it with the parameter's value and query.

The record is successfully entered into the table, as evidenced by the output mentioned above.

                    Function            Function Details
fetchall()     Returns the whole result set or any remaining rows.
fetchone()   If there are no records to return, none will be returned instead of the single row from the result.
fetchmany([size])  If there are no records to return, it will return[]. It will return the requested size of rows from the result sets. The initial size is one.

Let's use an example to describe the aforementioned methods.

#python py_mysql.py


# the library be imported
import mysql.connector


# establishing connection
con = mysql.connector.connect(
  host="localhost",
  user="Annu",
  password="Password",
  database ="db_test"
)


# from the connection, import the cursor (con)
my_cursor = con.cursor()


my_cursor.execute("SELECT * FROM STUDENT")


# Fetch the 1st row 
print (my_cursor.fetchone()) 
# Fetch the next four rows 
print (my_cursor.fetchmany(4))  
# Fetch all the remaining rows
print (my_cursor.fetchall())  
# The result set is now empty
print (my_cursor.fetchmany())  


# Closing the con and cursor
my_cursor.close()
con.close()

Output;

(1, 'Amit', 'IT')
[(2, 'Anshu', 'Commerce'), (3, 'Sonali', 'Science'), (4, 'Rohit', 'Commerce'), (5, 'Arpit', 'IT')]
[(6, 'Reyansh', 'Science'), (7, 'Ripunj', 'Atrs')]
[]

Line 20: The first record in the result sets is retrieved via the fetchone () method.

Line 22: The four records are retrieved from result sets by the fetchmany(4) function.

Line 24: All of the remaining records are retrieved from the result sets using the fetchall () method.

Line 26: The fetchmany () has a default size of 1, therefore it tries to get one record from result sets once more in line 26. But because the fetchmany (4) method and the fetchone () method have already accessed 4 and 1, respectively, it tries to retrieve the sixth tuple from record sets.

Function cursor.executemany():

In order to INSERT OR REPLACE numerous records at once, we can use the executemany () function. The executemany () function's syntax is as follows:

executemany (query, args)

Parameters:

  • query: This ought to be a string type.
  • Arguments: Since the arguments by default are None, we are unable to run the SELECT query in that. Values can be passed as either a list or a tuple.

Returns:

  • If any rows were impacted by the query, it will return a count of those rows.

ReturnType:

  • An integer will be used as the return type (int or None).

We'll now give a practical illustration of the aforementioned approach.

#python py_mysql.py


# the library be imported
import mysql.connector


# establishing a database connection
con = mysql.connector.connect(
  host="localhost",
  user="Annu",
  password="Password",
  database="db_test"
)


my_cursor = con.cursor()


# run the query using the value of their record.
query = 'INSERT INTO STUDENT (rollNo, Name, Subject) VALUES (%s, %s, %s)'
value = [(8, "Ankit", 'Arts'),
       (9, "Sruti", 'Science'),
       (10, "Mahima", "IT"),
       (11, "Aryan", "IT")
       ]
my_cursor.executemany(query,value)


# We store the data in a table.
con.commit()


print (my_cursor.rowcount, "record(s) inserted.")

Output:

4 record(s) inserted.

Now, see the data in the table

mysql> select * from student;
+--------+---------+----------+
| rollNo | Name    | Subject  |
+--------+---------+----------+
|      1 | Amit    | IT       |
|      2 | Anshu   | Commerce |
|      3 | Sonali  | Science  |
|      4 | Rohit   | Commerce |
|      5 | Arpit   | IT       |
|      6 | Reyansh | Science  |
|      7 | Ripunj  | Arts     |
|      8 | Ankit   | Arts     |
|      9 | Sruti   | Science  |
|     10 | Mahima  | IT       |
|     11 | Aryan   | IT       |
+--------+---------+----------+
11 rows in set (0.00 sec)


mysql>

Line 17: We formulate our insertion data query.

Line 18: To insert values into the table, we generate a list of values.

Line 25: To input the many records, we are using the executemany () function.

Use the execute () function to run many queries at once:

The single execute () method also allows us to run numerous queries. One more parameter, multi, is accepted by the execute () function. Multi is set to False by default. If we maintain multi=True, we can use the semicolon (;) separator to run a multi-sql query.

# python py_mysql.py


# the library be imported
import mysql.connector


# establishing connection
con = mysql.connector.connect(
  host="localhost",
  user="Annu",
  password="Password",
  database ="db_test"
)


# from the connection, import the cursor (con)
my_cursor = con.cursor()


# a format parameter style query


query1 = "select * from student"


query2 = 'INSERT INTO STUDENT (rollNo, Name, subject) VALUES (%s, %s, %s)'


queries = [query1,query2]


value = (12, "Aashish", 'Science')




multi_results = my_cursor.execute(";".join(queries), value, multi=True)


count = 1
for rslt in multi_results:


    # the outcome resembles a cursor,
    # so that we have access to all of the cursor's properties
    print ("query_{0} - {1} :".format(count, rslt.statement))
    if rslt.with_rows:
        for row in rslt:
            print (row)
        count = count + 1
    else:
        print ("No rslt")


    print ()


my_cursor.close()
con.close()

Output:

query_1 - select * from student :
(1, 'Amit', 'IT')
(2, 'Anshu', 'Commerce')
(3, 'Sonali', 'Science')
(4, 'Rohit', 'Commerce')
(5, 'Arpit', 'IT')
(6, 'Reyansh', 'Science')
(7, 'Ripunj', 'Arts')
(8, 'Ankit', 'Arts')
(9, 'Sruti', 'Science')
(10, 'Mahima', 'IT')
(11, 'Aryan', 'IT')


query_2 - INSERT INTO STUDENT (rollNo, Name, subject) VALUES (12, 'Aashish', 'Science') :
No rslt

Line 23: Two inquiries were made into a list.

Line 28: We provide the execute () function with the list of queries, values, and separator (;). Additionally, we switch multi's value from False to True.

We can see our multi-query results in the report up top.

Conclusion

In this article, the execute () function was explored. Various execute () method types, such as the executemany () method, have also been seen. Additionally, we looked at querying through the cursor. Execute the method () with its various parameters. Finally, we have seen how to use the execute () technique for solving several queries.


Related Topics

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.