Python: MySQL entry instance, pythonmysql

Source: Internet
Author: User

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.

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.