Python mysqldb Module Connection operation MySQL database instance _python

Source: Internet
Author: User

MySQL is a good open source database, it is now widely used, so it is necessary to briefly introduce the MySQL database using Python methods. Python operations database requires a third party module to be installed, with downloads and documentation in http://mysql-python.sourceforge.net/.

Since Python's database module has a specific database module specification, there is a demonstration of the code in the same way, regardless of which database is used:

#-*-encoding:gb2312-*-import OS, sys, string import mysqldb # Connection Database Try:conn = mysqldb.connect (host= ' localhost ', User= ' root ', passwd= ' xxxx ', db= ' test1 ') except Exception, E:print e sys.exit () # Get Cursor object to operate cursor = Conn.cursor () # Creating Table sql = "CREATE table if not exists test1 (name varchar (128) primary key, age int (4))" Cursor.execute (SQL) # Insert Data sq L = "INSERT into test1 (name, age) VALUES ('%s ',%d)"% ("Zhaowei") try:cursor.execute (SQL) except Exception, e:p rint e sql = "INSERT into test1 (name, age) VALUES ('%s ',%d)"% ("John," Try:cursor.execute (SQL) except Exception, E
  : Print e # insert Multiple sql = INSERT into test1 (name, age) values (%s,%s) val = (("Dick", 24), ("Harry", 25), ("Hong Liu,") Try: Cursor.executemany (SQL, Val) except Exception, e:print e #查询出数据 sql = "SELECT * from Test1" cursor.execute (SQL) ALLD ATA = Cursor.fetchall () # If there is data returned, loop output, AllData is a two-dimensional list if Alldata:for rec in Alldata:print rec[0], rec[1] Curs Or.close () Conn.close ()
 

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.