This article mainly introduces the tutorial on using MySQLdbforPython to operate databases in Python, describes the usage of MySQLdb in detail, and provides a good reference value for operating MySQL database program design in Python, for more information about how to use MySQLdb for Python to operate databases, see this article. 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:
The code is as follows:
Import MySQLdb
2. establish a connection with the database:
The 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.