Working with MySQL Getting started instance in Python

Source: Internet
Author: User
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.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.