Python access to MySQL Database implementation method (2 example)

Source: Internet
Author: User
This article describes how Python accesses the MySQL database. Share to everyone for your reference, as follows:

First install the mysqldb that matches the Python version

Example One

Import Mysqldbconn=mysqldb.connect (user= ' root ', passwd= ' 123 ', db= ' example ') cur=conn.cursor () Cur.execute ("SELECT ID , Lastname,firstname, Date_format (DOB, '%y-%m-%d%h-%i-%s '), phone from employee ") # #select Username,password, Date_ Format (reg_date, '%y-%m-%d%h-%i-%s ') as date from reg_userfor data in Cur.fetchall ():  print Datacur.close () Conn.commit () Conn.close ()

Example Two

Import Mysqldbconn = MySQLdb.connect (host= ' localhost ', user= ' root ', passwd= ') cursor = Conn.cursor () cursor.execute (" Create Database Python ") cursor.execute (' Use Python ') cursor.execute (" CREATE TABLE test (ID int, content varchar (100)) ") # Insert a 100 data for I in range (1,100):   cursor.execute ("INSERT into test values (%s,%s)", [I, ' haha ']) #获取数据cursor. Execute ( ' SELECT * from Test ') results = Cursor.fetchall () for R in results   print rconn.close ()

I hope this article is helpful for Python program design.

  • 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.