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使用turtle库绘制树

本文实例为大家分享了python使用turtle库绘制树的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ Spyder Editor...

在Django的form中使用CSS进行设计的方法

修改form的显示的最快捷的方式是使用CSS。 尤其是错误列表,可以增强视觉效果。自动生成的错误列表精确的使用`` <ul class=”errorlist”>``,这样,我...

pytorch方法测试详解——归一化(BatchNorm2d)

pytorch方法测试详解——归一化(BatchNorm2d)

测试代码: import torch import torch.nn as nn m = nn.BatchNorm2d(2,affine=True) #权重w和偏重将被使用 in...

flask + pymysql操作Mysql数据库的实例

flask + pymysql操作Mysql数据库的实例

安装flask-sqlalchemy、pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍...

python 基于TCP协议的套接字编程详解

基于TCP协议的套接字编程 实现电话沟通为例,这里传递的是字符,可以自己尝试去发送一个文件 # 服务端 import socket # 1. 符合TCP协议的手机 server =...