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

相关文章

python 使用装饰器并记录log的示例代码

1.首先定义一个log文件 # -*- coding: utf-8 -*- import os import time import logging import sys log_d...

python实现的重启关机程序实例

本文实例讲述了Python实现的重启关机程序的方法,对Python程序设计有一定的参考价值。具体方法如下: 实例代码如下: #!/usr/bin/python #coding=utf...

详解Python进程间通信之命名管道

管道是一种简单的FIFO通信信道,它是单向通信的。 通常启动进程创建一个管道,然后这个进程创建一个或者多个进程子进程接受管道信息,由于管道是单向通信,所以经常需要创建两个管道来实现双向通...

python编写微信公众号首图思路详解

python编写微信公众号首图思路详解

前言 之前一直在美图秀秀调整自己的微信公众号首图,效果也不尽如人意,老是调来调去,最后发出来的图片被裁剪了一大部分,丢失部分关键信息,十分恼火,于是想着用python写一个程序,把微信公...

Python简单计算数组元素平均值的方法示例

Python简单计算数组元素平均值的方法示例

本文实例讲述了Python简单计算数组元素平均值的方法。分享给大家供大家参考,具体如下: Python 环境:Python 2.7.12 x64 IDE :  &nb...