Operate mysql database with python (simple query operation)
1. Mysql installation
Ten thousand words are omitted here.
2. Pip installs the MySQLdb module
Sudo pip install mysql-python
3. Simple code
#! / usr/bin/env python#-*-coding: utf-8-*-import MySQLdb# establish a connection conn = MySQLdb.connect (host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db') cur = conn.cursor () # create a cursor # description: connect method generates a connection object Access the database through this object # manipulate the data res = cur.execute ('select * from UserInfo') # execute the sql statement data = cur.fetchall () # read the execution result # close the database connection cur.close () conn.close () print res # print out how many pieces of data print data # print the actual content of the data
4. Query the data of the specified ID number
#! / usr/bin/env python#-*-coding: utf-8-*-import MySQLdb# establish a connection conn = MySQLdb.connect (host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db') cur = conn.cursor () # manipulate the data sql = "select * from user where id=%s" # define sql statement params = ('3') # Parameter ID is 3cur.execute (sql Params) # execute the sql statement data = cur.fetchall () # close the database connection cur.close () conn.close () print data