Python操作MySQL简单实现方法

yipeiwu_com5年前Python基础

本文实例讲述了Python操作MySQL简单实现方法。分享给大家供大家参考。具体分析如下:

一、安装:

安装MySQL

安装MySQL不用多说了,下载下来安装就是,没有特别需要注意的地方。

一个下载地址:点击打开链接

二、示例:

复制代码 代码如下:
# 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',24,'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 "插入之后"
   #查询
   Select(cur)
   #更新
   Update(cur)
   print "更新之后"
   #查询
   Select(cur)
   #删除
   Delete(cur)
   print "删除之后"
   #查询
   Select(cur)
   
   cur.close()
   conn.close()
   
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python+pyqt实现12306图片验证效果

python+pyqt实现12306图片验证效果

本文实例为大家分享了python实现12306图片验证效果的具体代码,供大家参考,具体内容如下 思路:在鼠标点击位置加一个按钮,然后再按钮中的点击事件中写一个关闭事件. #codin...

Django框架 querySet功能解析

可切片 使用Python 的切片语法来限制查询集记录的数目 。它等同于SQL 的LIMIT 和OFFSET 子句。 >>> Entry.objects.all()...

Python实现八大排序算法

如何用Python实现八大排序算法 1、插入排序 描述 插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间...

python实现给scatter设置颜色渐变条colorbar的方法

python实现给scatter设置颜色渐变条colorbar的方法

python设置scatter颜色渐变的方法 参考代码如下: <span style="font-size:18px;">import matplotlib.pyplot...

解决vscode python print 输出窗口中文乱码的问题

一、搭建 python 环境 在 VSC 中点击 F1 键,弹出控制台,输入 ext install 界面左侧弹出扩展窗格,输入python,确认,开始搜索 下载发布者为Don Jaya...