Python database operation tutorial using MySQLdb for Python, pythonmysqldb
This article describes how to use MySQLdb for Python to operate databases. The details are as follows:
Generally, websites need to interact with databases. Otherwise, nothing needs to be done. Today, we will analyze a database named MySQLdb and use it to interact with the MySQL database.
You can obtain this library from here:
Http://sourceforge.net/projects/mysql-python
If you are not sure whether this library is available in your python environment, open the python shell and input import MySQLdb. If the error message is returned, it indicates that there is no such database on your machine, download one. my machine is Windows xp, So I downloaded the exe in the Windows environment and double-click it to complete the installation.
Before introducing specific operations, let's talk about how a program interacts with a database:
1. Establish a connection with the database
2. Execute SQL statements and receive the returned values.
3. Close database connection
Follow the steps above to use MySQLdb. Let's proceed step by step.
1. Introduce the MySQLdb Library:
Copy codeThe Code is as follows: import MySQLdb
2. Establish a connection with the database:
Copy codeThe Code is as follows: conn = MySQLdb. connect (host = "localhost", user = "root", passwd = "sa", db = "mytable ")
The connect method is used to establish a connection with the database, receive several parameters, and return the connection object.
Common parameters include:
Host: specifies the Database host name. The local host is used by default.
User: Database login name. The default value is the current user.
Passwd: Password for database login. Empty by default.
Db: name of the database to be used. No default value exists.
Port: the TCP port used by the MySQL service. The default value is 3306.