Python: MySQL entry instance, pythonmysql
1. Install MySQL-python
Copy codeThe Code is as follows:
# Yum install-y MySQL-python
2. Open a database connection
Copy codeThe Code is as follows:
#! /Usr/bin/python
Import MySQLdb
Conn = MySQLdb. connect (user = 'root', passwd = 'admin', host = '2017. 0.0.1 ')
Conn. select_db ('test ')
Cur = conn. cursor ()
Iii. Database Operations
Copy codeThe Code is as follows:
Def insertdb ():
SQL = 'insert into test (name, 'sort ') values ("% s", "% s ")'
Exsql = SQL % ('hello', 'python ')
Cur.exe cute (exsql)
Conn. commit ()
Return 'insert success'
Def selectdb ():
SQL = 'select 'name' from test where 'sort '= "% s "'
Exsql = SQL % ('python ')
Count = cur.exe cute (exsql)
For row in cur:
Print row
Print 'cursor move to top :'
Cur. scroll (0, 'absolute ')
Row = cur. fetchone ()
While row is not None:
Print row
Row = cur. fetchone ()
Print 'cursor move to top :'
Cur. scroll (0, 'absolute ')
Iterator = cur. fetchiterator (count)
Print response
Def deletedb ():
SQL = 'delete from test where 'sort '= "% s "'
Exsql = SQL % ('python ')
Cur.exe cute (exsql)
Conn. commit ()
Return 'delete success'
Print insertdb ()
Print insertdb ()
Selectdb ()
Print deletedb ()
4. Close the connection
Copy codeThe Code is as follows:
Cur. close ()
Conn. close ()
Pay attention to the sequence.