×

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

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python pycountry

What is Pycountry? Python programming language: 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...

4 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

How to Install Numpy in PyCharm

What is PyCharm? JetBrains created the hybrid platform known as PyCharm as a Python IDE. The Python IDE PyCharm is used by some major companies, including Twitter, Facebook, Amazon, and many...

4 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

GUI to Shut down, Restart and Logout from the PC using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

4 minutes read.