一,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. 《Maven实战》第5章 坐标和依赖

    5.1 Maven坐标——项目唯一标识 groupId(必须定义):定义Mavan项目隶属的实际项目,如SpringFramework,一个实际项目可包含多个Maven项目 artifactId(必须 ...

  2. AtCoder Regular Contest 095

    AtCoder Regular Contest 095 C - Many Medians 题意: 给出n个数,求出去掉第i个数之后所有数的中位数,保证n是偶数. \(n\le 200000\) 分析: ...

  3. spark学习(RDD案例实战)

    练习0(并行化创建RDD) 先启动spark-shell 通过并行化生成rdd scala> val rdd1 = sc.parallelize(List(63,45,89,23,144,777 ...

  4. make install报错

    今天,在运行公司内核的机器上,编译标准内核,结果提示: 问题原因: 原来安装新内核的时候,会与原内核比较,如果缺少了某些模块,就会提示”ERROR: modinfo: could not find m ...

  5. 缓存技术内部交流_01_Ehcache3简介

    参考资料: http://www.ehcache.org/documentation/3.2/getting-started.html http://www.ehcache.org/documenta ...

  6. js中object的copy

    一.场景 在js中一个对象(Object)或者是一个数组(Array)在复制的过程中往往不是特别的简单,一般情况下我们会直接将其赋值给另外一个变量名下,就像这样: var a = [1,2,3]; v ...

  7. Python 导出数据from Mysql

    环境 Anaconda3 Python 3.6, Window 64bit 目的 从MySQL数据库读取目标表数据,并处理 代码 # -*- coding: utf-8 -*- import pand ...

  8. IOS-社会化分享

    一.如何实现社交分享 在iOS中,实现“社交分享”的方法 1.自己编写各个平台的分享代码(代码量较多)   2.利用iOS自带的Social.framework   3.利用第三方的分享框架 友盟分享 ...

  9. 转:session和cookie以及catch三者的区别

    以前实现数据的缓存有很多种方法,有客户端的Cookie,有服务器端的Session和Application. 其中Cookie是保存在客户端的一组数据,主要用来保存用户名等个人信息. Session则 ...

  10. LeetCode OJ:First Bad Version(首个坏版本)

    You are a product manager and currently leading a team to develop a new product. Unfortunately, the ...