In this Python MySQL tutorial we want to learn about Python MySQL Connection, so Python is popular programming language and it is used in different types of applications, for example we can use Python for web development, data analysis and machine learning. MySQL is one of the most widely used relational database management systems (RDBMS), and it is often used together with Python to create scalable applications. in this article we want to talk that how to establish a connection between Python and MySQL.
For establishing a connection between Python and MySQL, we need to install a Python package called mysql-connector-python. this package provides Python interface for connecting to MySQL database, and can be installed using pip.
1 |
pip install mysql-connector-python |
After that the package is installed, we can establish a connection to MySQL database using connect() method provided by mysql.connector module.
This is an example, in this example we are establishing a connection to MySQL database located on the local machine, using a username and password for authentication. we also specify the name of the database we want to connect.
1 2 3 4 5 6 7 8 9 10 |
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) print(mydb) |
After that the connection is established to MySQL database, we can execute SQL queries using cursor() method provided by the MySQLConnection object.
This is an example, in this example we are executing a SELECT query on a table called book in the MySQL database. fetchall() method is used to retrieve all the rows in the result set, and we iterate over the rows and print them to the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM book") myresult = mycursor.fetchall() for x in myresult: print(x) |
This will be the result
