In this Python tutorial we want to learn about Python SQL Integration, so Python and SQL are two powerful tools in the world of data analytics and management. Python is a powerful programming language with different libraries that you can easily use for database functionalities. SQL on the other hand is standard language for managing relational databases. integrating these two tools can provide powerful capabilities for data analysts, scientists and engineers.
In this article we want to talk that how to integrate Python and SQL, and some of the advantages of this.
Python SQL Integration
Python offers several libraries for connecting to SQL databases.
PyODBC | This is a Python module that allows developers to connect to any database that has an ODBC driver installed. |
SQLAlchemy | A SQL toolkit and Object-Relational Mapping (ORM) library for Python that provides a set of high-level APIs for connecting to various databases. |
pymysql | A pure-Python MySQL driver that allows developers to interact with MySQL databases from within Python. |
Now let’s learn that how we can connect Python with MySQL database using pymysql, in this example, first of all we have established a connection to the MySQL database using connect() method provided by pymysql. after that we have created a cursor object, which we use to execute a SQL query. and lastly we fetch all the rows returned by the query using the fetchall() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import pymysql # Open database connection db = pymysql.connect(host="localhost",user="root",password="",database="new") # Prepare a cursor object cursor = db.cursor() # Execute SQL query cursor.execute("SELECT * FROM book") # Fetch all rows rows = cursor.fetchall() for row in rows: print("ID : " + str(row[0])) print("Title : " + row[1]) print("Author : " + row[2]) print("Price : " + str(row[3])) # Close database connection db.close() |
If you run the code this will be the result

Note: Make sure that you already have installed PyMySQL
1 |
pip install pymysql |