Python operation MySQL Simple implementation method

Source: Internet
Author: User
In this paper, we describe the simple implementation method of Python operation MySQL. Share to everyone for your reference. The specific analysis is as follows:

First, Installation:

Install MySQL

Install MySQL Needless to say, download the installation is, there is no special need to pay attention to the place.

One download address: Click the Open link

Second, example:
Copy the Code code as follows:

# Coding=utf-8
Import MySQLdb

#查询数量
def Count (cur):
Count=cur.execute (' select * from Student ')
print ' There has%s rows record '% count

#插入
def Insert (cur):
sql = "INSERT into Student (id,name,age,sex) VALUES (%s,%s,%s,%s)"
param = (2, ' xiaoming ', +, ' boy ')
Cur.execute (Sql,param)

#查询
def Select (cur):
n = Cur.execute ("SELECT * from Student")
Print "------"
For row in Cur.fetchall ():
For R in row:
Print R
Print "------"
#更新
def Update (cur):
sql = "Update Student set Name =%s where ID = 2"
param = ("Xiaoxue")
Count = Cur.execute (Sql,param)

#删除
def Delete (cur):
sql = "Delete from Student where Name =%s"
param = ("Xiaoxue")
n = Cur.execute (Sql,param)

Try
Conn=mysqldb.connect (host= ' localhost ', user= ' root ', passwd= ' 123456 ', db= ' python ', port=3306)
Cur=conn.cursor ()
#数量
Count (cur)
#查询
Select (cur)
#插入
Insert (cur)
Print "After Insert"
#查询
Select (cur)
#更新
Update (cur)
print "After Update"
#查询
Select (cur)
#删除
Delete (cur)
print "After delete"
#查询
Select (cur)

Cur.close ()
Conn.close ()

Except Mysqldb.error,e:
Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

Hopefully this article will help you with Python programming.

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