Python database operations

Source: Internet
Author: User

If it's a jar, then the first thing to do is jar package, install Pymysql with PIP (Note: I'm using Python 3.5)

ImportOS, sys, stringImportPymysql#connecting to a databaseTry:    #conn = pymysql.connect (host= ' localhost ', user= ' root ', passwd= ' root ', db= ' test ', charset= ' UTF8 ')conn = Pymysql.connect (host='127.0.0.1', port=3306,user='Root', passwd='Root', db='Test', charset='UTF8')exceptException as E:Print(e) sys.exit ()#get the Cursor object to manipulatecursor=conn.cursor ()#Create a tablesql ="CREATE table if not exists test1 (name varchar (+) primary key, age int (4))"cursor.execute (SQL)#Inserting Datasql ="INSERT into Test1 (name, age) VALUES ('%s ',%d)"% ("Zhaowei", 23)Try: Cursor.execute (SQL)exceptException as E:Print(e) SQL="INSERT into Test1 (name, age) VALUES ('%s ',%d)"% ("Zhang San"21st)Try: Cursor.execute (SQL)exceptException as E:Print(e)#insert more than oneSQL="INSERT into Test1 (name, age) values (%s,%s)"Val= (("John Doe", 24), ("Harry", 25), ("Hong Lu", 26))Try: Cursor.executemany (SQL, Val)exceptException as E:Print(e)#Querying out Datasql ="SELECT * from Test1"cursor.execute (SQL) AllData=Cursor.fetchall ()#If there is data returned, the loop output, AllData is a two-dimensional listifAllData: forRecinchAllData:Print(Rec[0], rec[1]) Conn.commit () Cursor.close () conn.close ()

It is said that after Python 3 the exception is captured to write except Exception as E:, previously except Exception, E:

Python database operations

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.