First, install the Mysql-python
Copy CodeThe code is as follows:
# yum Install-y Mysql-python
Second, open the database connection
Copy CodeThe code is as follows:
#!/usr/bin/python
Import MySQLdb
conn = MySQLdb.connect (user= ' root ', passwd= ' admin ', host= ' 127.0.0.1 ')
conn.select_db (' Test ')
cur = conn.cursor ()
third, the operation of the database
Copy CodeThe code is as follows:
Def insertdb ():
sql = ' INSERT into test (name, ' sort ') values ("%s", "%s") '
exsql = sql% (' hello ', ' python ')
Cur.execute (Exsql)
Conn.commit ()
Return ' Insert Success '
Def selectdb ():
sql = ' SELECT ' name ' from test where ' sort ' = '%s '
exsql = sql% (' python ')
Count = Cur.execute (exsql)
For row in cur:
Print row
print ' cursor move to top: '
Cur.scroll (0, ' absolute ')
row = Cur.fetchone ()
While row was not None:
Print row
row = Cur.fetchone ()
print ' cursor move to top: '
Cur.scroll (0, ' absolute ')
many = Cur.fetchmany (count)
Print many
Def deletedb ():
sql = ' Delete from test where ' sort ' = '%s ' '
exsql = sql% (' python ')
Cur.execute (Exsql)
Conn.commit ()
Return ' Delete Success '
Print Insertdb ()
Print Insertdb ()
Selectdb ()
Print Deletedb ()
Four, close the connection
Copy the Code code as follows:
Cur.close ()
Conn.close ()
Note the order.