Python operation MySQL simple implementation method
- 2020-04-02 14:31:32
- OfStack
This article illustrates a simple implementation of Python operation of MySQL. Share with you for your reference. Specific analysis is as follows:
I. installation:
MySQL installation
Installation of MySQL needless to say, download down the installation is, there is no special need to pay attention to the place.
A download address: click the open link
Ii. Examples:
# coding=utf-8
import MySQLdb
# The number of queries
def Count(cur):
count=cur.execute('select * from Student')
print 'there has %s rows record' % count
# insert
def Insert(cur):
sql = "insert into Student(ID,Name,Age,Sex)values(%s,%s,%s,%s)"
param = (2,'xiaoming',24,'boy')
cur.execute(sql,param)
# The query
def Select(cur):
n = cur.execute("select * from Student")
print "------"
for row in cur.fetchall():
for r in row:
print r
print "------"
# update
def Update(cur):
sql = "update Student set Name = %s where ID = 2"
param = ("xiaoxue")
count = cur.execute(sql,param)
# delete
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()
# The number of
Count(cur)
# The query
Select(cur)
# insert
Insert(cur)
print " After insertion "
# The query
Select(cur)
# update
Update(cur)
print " After the update "
# The query
Select(cur)
# delete
Delete(cur)
print " After deleting "
# The query
Select(cur)
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
I hope this article has helped you with your Python programming.