MySQL is currently one of the most popular open source relational database management systems. Python is a high-level programming language. The two can be used in combination. This article will introduce how to install and use MySQL in python.
Step one: Install MySQL
Before installing MySQL, make sure that the host has installed Python, as well as pip, the Python package management tool.
The current official download address of MySQL is: https://dev.mysql.com/downloads/mysql/
After the download is completed, execute the following command to install MySQL:
$ sudo apt-get install mysql-server
If the MySQL installation is successful, you can Start MySQL through the following command:
$ sudo service mysql start
After starting MySQL, we can use the following command to log in to MySQL:
$ mysql -u 用户名 -p
Step 2 :Install the MySQL driver for Python
Install the MySQL driver for Python. We can use MySQL-Python or mysqlclient to install As follows:
$ pip install MySQL-python
Another mysql driver is PyMySQL, install it as follows:
$ pip install PyMySQL
Step 3: Use it in Python MySQL
To use MySQL in a Python program, you first need to connect to the MySQL database. We can use the following code to connect to MySQL:
import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="your_password", db="your_database_name")
The following code can be used to execute SQL commands:
import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="your_password", db="your_database_name") cursor = db.cursor() sql = "SELECT * FROM your_table_name" cursor.execute(sql) result_set = cursor.fetchall() for row in result_set: print row[0], row[1]
Finally, if you no longer use MySQL, close the connection to release resources:
import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="your_password", db="your_database_name") cursor = db.cursor() sql = "SELECT * FROM your_table_name" cursor.execute(sql) result_set = cursor.fetchall() db.close()
Summary:
MySQL is a popular database management system, and Python is a flexible, easy-to-learn, and easy-to-use programming language. Combining the two can improve development efficiency. This article introduces how to install and use MySQL in python.
The above is the detailed content of mysql python installation. For more information, please follow other related articles on the PHP Chinese website!