一,MySQL-Python插件
      Python里操作MySQL数据库,需要Python下安装访问MySQL数据库接口API包即插件,从而使得Python2.7能访问操作MySQL数据库。MySQL软件可以去官网下载:http://www.mysql.com/; MySQLdb插件下载:http://sourceforge.net/projects/mysql-python/files/latest/download
二,访问MySQL数据库
    1,连接数据库mysql
         基本格式:connect ([host=]'ip',[user=]'user',[passwd=]'password',[db=]'dbname')
    2,数据库的基本操作
     1)create创建表
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#create a table
cursor.execute('create table \
test(ID int primary key auto_increment,Name char(25))')
#Closing database
cursor.close()
conn.close()
     2)fetchall访问:
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close() >>> ================================ RESTART ================================
>>>
3 ((4L, 'zhangbc'), (5L, 'lis08'), (6L, 'wangw'))
>>>
 
在Mysql5.6环境下运行:
3)insert向表中插入数据:
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#insert data into table 'test'
mysql='''insert into test(id,sname) values(4,'zhanghua')'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close() >>> ================================ RESTART ================================
>>>
4 ((1L, 'zhangbc'), (2L, 'lis'), (3L, 'wangw'), (4L, 'zhanghua'))
注意:一定要写上conn.commit();事物不提交,将回滚。比较:
 
4)update修改表中数据:
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#update data of the table 'test'
mysql='''update test set sname='Lisi08' where id=2'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close() >>> ================================ RESTART ================================
>>>
4 ((1L, 'zhangbc'), (2L, 'Lisi08'), (3L, 'wangw'), (4L, 'zhanghua'))
5)delete删除表中数据:
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#delete data of the table 'test'
mysql='''delete from test where id=4'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close() >>> ================================ RESTART ================================
>>>
3 ((1L, 'zhangbc'), (2L, 'Lisi08'), (3L, 'wangw'))
     6)关于select及其遍历:
      i)使用元组tuple与fetchone结合
 import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#fetch datas
cursor.execute('select * from test;')
#获得结果集的记录
numrows=int(cursor.rowcount)
#循环,取行数据
for i in range(numrows):
row=cursor.fetchone()
print row[0],row[1]
#Closing database
cursor.close()
conn.close() >>> ================================ RESTART ================================
>>>
4 zhangbc
5 lis08
6 wangw

ii)使用字典cursor

 #-*- coding:UTF-8 -*-
import MySQLdb as mdb
#connect to a database 'test'
conn=mdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
with conn:
#获取连接上的字典cursor,每一个cursor其实都是cursor的子类
cur=conn.cursor(mdb.cursors.DictCursor)
#fetch datas
cur.execute('select * from test;')
#获得结果集
rows=cur.fetchall()
#循环,取行数据
for row in rows:
print '%s %s'%(row['ID'],row['Name'])
#Closing database
cur.close()
conn.close() >>> ================================ RESTART ================================
>>>
4 zhangbc
5 lis08
6 wangw

iii)获取单个表的字段名及其信息

 #-*- coding:UTF-8 -*-
import MySQLdb as mdb
#connect to a database 'test'
conn=mdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
with conn:
#获取连接上的字典cursor,每一个cursor其实都是cursor的子类
cur=conn.cursor()
#fetch datas
cur.execute('select * from test;')
#获得结果集
rows=cur.fetchall()
#获得链接对象的描述信息
desc=cur.description
print 'cur.description:',desc
#打印表头
print '%2s %3s'%(desc[0][0],desc[1][0])
#循环,取行数据
for row in rows:
print '%2s %3s'%row
#Closing database
cur.close()
conn.close() >>> ================================ RESTART ================================
>>>
cur.description: (('ID', 3, 1, 11, 11, 0, 0), ('Name', 254, 7, 25, 25, 0, 1))
ID Name
4 zhangbc
5 lis08
6 wangw
三,小结
     本文主要介绍了Python下如何访问并操数据库的基本知识,如:如何连接数据库,如何执行执行SQL语句等等。
 

Python学习系列(七)( 数据库编程)的更多相关文章

  1. python学习笔记(七):面向对象编程、类

    一.面向对象编程 面向对象--Object Oriented Programming,简称oop,是一种程序设计思想.在说面向对象之前,先说一下什么是编程范式,编程范式你按照什么方式来去编程,去实现一 ...

  2. Python学习系列(八)( 面向对象基础)

     Python学习系列(八)( 面向对象基础) Python学习系列(七)( 数据库编程) 一,面向对象 1,域:属于一个对象或类的变量.有两种类型,即实例变量—属于每个实例/类的对象:类变量—属于类 ...

  3. Python学习系列(六)(模块)

    Python学习系列(六)(模块) Python学习系列(五)(文件操作及其字典) 一,模块的基本介绍 1,import引入其他标准模块 标准库:Python标准安装包里的模块. 引入模块的几种方式: ...

  4. Python学习系列(三)(字符串)

    Python学习系列(三)(字符串) Python学习系列(一)(基础入门) Python学习系列(二)(基础知识) 一个月没有更新博客了,最近工作上有点小忙,实在是没有坚持住,丢久又有感觉写的必要了 ...

  5. Python学习系列(二)(基础知识)

    Python基础语法 Python学习系列(一)(基础入门) 对于任何一门语言的学习,学语法是最枯燥无味的,但又不得不学,基础概念较繁琐,本文将不多涉及概念解释,用例子进行相关解析,适当与C语言对比, ...

  6. python学习之路网络编程篇(第四篇)

    python学习之路网络编程篇(第四篇) 内容待补充

  7. python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍

    目录 python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍 一丶元祖 1.元祖简介 2.元祖变量的定义 3.元祖变量的常用操作. 4.元祖的遍历 5.元祖的应用场景 p ...

  8. Python学习第七课

    Python学习第七课 'Alex' "Alex"print('hello'*5) #重复输出字符串 print('hellowold'[2:]) #类似于切片操作:会取出 llo ...

  9. Python学习系列(九)(IO与异常处理)

    Python学习系列(九)(IO与异常处理) Python学习系列(八)( 面向对象基础) 一,存储器 1,Python提供一个标准的模块,称为pickle,使用它既可以在一个文件中存储任何Pytho ...

随机推荐

  1. Luogu-3250 [BJOI2017]魔法咒语(AC自动机,矩阵快速幂)

    Luogu-3250 [BJOI2017]魔法咒语(AC自动机,矩阵快速幂) 题目链接 题解: 多串匹配问题,很容易想到是AC自动机 先构建忌讳词语的AC自动机,构建时顺便记录一下这个点以及它的所有后 ...

  2. 金中半日baoling游-----stoi

    蒟蒻又来水博客了,写个游记啦啦啦啦,好像是第一篇游记咯. 温馨提示:愚人节写的博客看了后会变棒棒哦!(麻麻再也不用担心我被骗) 进入正题 3月31日早6:30左右起床了,然后就是....(此处可省略) ...

  3. NOIP2018没有什么新闻

    noip结束了.站在六中门口,回头望了一眼偌大的校园,萧瑟的秋风卷起残败的落叶,纷纷扬扬地洒落,洒落在OIer的心头. 今年的noip没有什么新闻,有的只是又一次被喷的题,和又一次挂掉的我. Day ...

  4. sql报字段过大的错误解决方法

    set global max_allowed_packet = 2*1024*1024*10

  5. oracle 10g和11g将表到缓存到内存中

    alter table 表名 cache;alter table 表名 storage(buffer_pool keep);

  6. 一个Elasticsearch嵌套nested查询的实例

    创建索引和数据准备 PUT course PUT course/_mapping/course { "properties": { "course":{ &qu ...

  7. 间隔问题,合并间隔(merge interval),插入间隔(insert interval)

    Merge Interval: Given a collection of intervals, merge all overlapping intervals. For example,Given  ...

  8. 使用ssm整合是创建Maven项目报错Failure to transfer com.thoughtworks.xstream:xstream:pom:1.3.1

    Description Resource Path Location TypeFailure to transfer com.thoughtworks.xstream:xstream:pom:1.3. ...

  9. php将科学计算法得出的结果转换成原始数据

    由于php最大只支持显示 15位因的数据运算,大于15位的2数加减乘除的数据的结果,会直接用科学计数法显示, 但在现实生活中,科学计数法不利于普通人识别,所以,本函数将:科学计数法的出的结果转换成原始 ...

  10. Ceph:pg peering过程分析

    转自:https://www.ustack.com/blog/ceph%ef%bc%8dpg-peering/ Peering:互为副本的三个(此处为设置的副本个数,通常设置为3)pg的元数据达到一致 ...