First, install the Mysql-python
Yum Install -y Mysql-python
Second, open the database connection
# !/usr/bin/python Import = MySQLdb.connect (user='root', passwd='admin', host='127.0.0.1') conn.select_db ('test') = Conn.cursor ()
third, the operation of the database
definsertdb (): SQL='INSERT into Test (name, ' sort ') values ("%s", "%s")'Exsql= sql% ('Hello','python') returnCur.execute (exsql)defselectdb (): SQL='Select ' name ' from test where ' sort ' = '%s ''Exsql= sql% ('python') Count=Cur.execute (exsql) forRowinchcur:PrintRowPrint 'cursor move to top:'cur.scroll (0,'Absolute') Row=Cur.fetchone () whileRow is notNone:PrintRow Row=Cur.fetchone ()Print 'cursor move to top:'cur.scroll (0,'Absolute') Many=Cur.fetchmany (count)Printmanydefdeletedb (): SQL='Delete from test where ' sort ' = '%s ''Exsql= sql% ('python') returnCur.execute (exsql)PrintInsertdb ()PrintInsertdb () selectdb ( )PrintDeletedb ()
Four, close the connection
Cur.close () Conn.close ()
Note the order.
Python Learning Note 11: Working with MySQL