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 pandas模块基础学习详解

Pandas类似R语言中的数据框(DataFrame),Pandas基于Numpy,但是对于数据框结构的处理比Numpy要来的容易。 1. Pandas的基本数据结构和使用 Panda...

pytorch之inception_v3的实现案例

如下所示: from __future__ import print_function from __future__ import division import torch i...

Python从数据库读取大量数据批量写入文件的方法

使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将数据加载进内存,这时我们需要将数据进行预处理,分批次加载进内存。 下面是代码作用是将数据从数据库读取出来分批次写入txt文本文...

Python中的异常处理简明介绍

python异常处理机制和java类似,采用try-except-finally的结构. try-except检测异常 格式 复制代码 代码如下: try:   &n...

基于Python 的进程管理工具supervisor使用指南

基于Python 的进程管理工具supervisor使用指南

Supervisor 是基于 Python 的进程管理工具,只能运行在 Unix-Like 的系统上,也就是无法运行在 Windows 上。Supervisor 官方版目前只能运行在 P...