Python operation MySQL Database

Source: Internet
Author: User

MySQLdb operation of MySQL database. Let's start with a simple example:

1 ImportMySQLdb2  3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', db='Test', port=3306)5Cur=conn.cursor ()6Cur.execute ('SELECT * from user')7 cur.close ()8 conn.close ()9 exceptmysqldb.error,e:Ten      Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

Insert data, BULK INSERT data, update data!

1 ImportMySQLdb2  3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', port=3306)5Cur=conn.cursor ()6      7Cur.execute ('CREATE database if not exists Python')8conn.select_db ('python')9Cur.execute ('CREATE TABLE Test (ID int,info varchar )')Ten       OneValue=[1,'Hi Rollen'] ACur.execute ('INSERT into test values (%s,%s)', value) -       -values=[] the      forIinchRange (20): -Values.append ((I,'Hi Rollen'+str (i))) -           -Cur.executemany ('INSERT into test values (%s,%s)', values) +   -Cur.execute ('Update test set info= "I am Rollen" where id=3') +   A Conn.commit () at cur.close () - conn.close () -   - exceptmysqldb.error,e: -      Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

Please note that you must have conn.commit () to commit the transaction , or you cannot actually insert the data.

1 ImportMySQLdb2  3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', port=3306,charset= ' UTF8 ')5Cur=conn.cursor ()6      7conn.select_db ('python')8  9Count=cur.execute ('SELECT * FROM Test')Ten     Print 'There has%s rows record'%Count One   Aresult=Cur.fetchone () -     Printresult -     Print 'ID:%s Info%s'%result the   -Results=cur.fetchmany (5) -      forRinchResults: -         PrintR +   -     Print '=='*10 +Cur.scroll (0,mode='Absolute') A   atresults=Cur.fetchall () -      forRinchResults: -         PrintR[1] -       -   - Conn.commit () in cur.close () - conn.close () to   + exceptmysqldb.error,e: -      Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

Python operation MySQL Database

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.