1. Import Module
Import MySQLdb >>> help ('mysqldb ')
>>> Help ('mysqldb. cursors ')
2. Connect to the database
Conn = MySQLdb. Connection (host = 'host', user = 'user', passwd = 'Password', db = 'dbname', port = port)
For example:
Conn = connect (host = '10. 0. *. * ', user = 'root', db = 'mysql', port = 3306, passwd = 'test ')
Meaning:
Host: ip address of the host that needs to be connected to Mysql
User: user name used to connect to mysql
Password: user name and password used for connection
Dbname: Default opened database
If you need to switch to another database of the user after the connection is successful, use the following statement:
Conn. select_db ('database name') 3. Obtain the database operation cursor (pointer)
Because the underlying layer of this module actually calls c api, you must first obtain the pointer to the database.
Cur = conn. cursor () 4. Database Operations
Execute the SQL query statement using the pointer object first:
Cur.exe cute ('select * from tables ')
The returned value is the number of rows obtained by the SQL statement. For example, 2L indicates 2 rows.
Then, you can obtain the row information from the fetchone or fetchall methods of the object.
The fetchone () method of the pointer object is to get the tuple return value of a row each time:
- >>> Result = cur. fetchone ()
- >>>PrintResult
The fetchall () method of the pointer object is to obtain a set of tuple values composed of row information:
- >>> Cur. scroll (0,'Absolute')
- >>> Result = cur. fetchall ()
- >>>PrintResult