Python操作MySQL简单实现方法

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Appium Python自动化测试之环境搭建的步骤

Appium Python自动化测试之环境搭建的步骤

Appium简介 Appium是一个自动化测试开源工具,支持IOS和Android平台上的移动原生应用、移动Web应用和混合应用。所谓的“移动原生应用”是指那些用IOS或者Android...

python 读取更新中的log 或其它文本方式

在项目中遇到这个问题,想把本地的log文件通过 Server-Send Event 的形式 发送给前端。 但是如何把那些 新增加log文本 读取出来就成了问题。 想过遍历log文件取得行...

Python3.6 Schedule模块定时任务(实例讲解)

Python3.6 Schedule模块定时任务(实例讲解)

一,编程环境 PyCharm2016,Anaconda3 Python3.6 需要安装schedule模块,该模块网址:https://pypi.python.org/pypi/sche...

python实现用户登陆邮件通知的方法

本文实例讲述了python实现用户登陆邮件通知的方法。分享给大家供大家参考。具体如下: 这里写在linux计划任务里定时执行,当有新用户登陆时候发送用户名到指定邮箱通知管理员。 #!...

Python装饰器的执行过程实例分析

本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下: 今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭...