一,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. 【React Native开发】React Native进行签名打包成Apk

    转载请标明出处: http://blog.csdn.net/developer_jiangqq/article/details/50525976 本文出自:[江清清的博客] (一)前言 [好消息]个人 ...

  2. Python 面向对象的三大特性:封装,继承,多态

    # 面向对象的三大特性:封装,继承,多态 # 继承的影响:资源的继承,资源的使用,资源的覆盖,资源的累加 # 资源的继承,在Python中的继承是指能使用父类的资源,而不是说在子类也复制一份父类代码到 ...

  3. 读取Excel复杂的数据

    涉及到合并单元格的数据读取: package com.util; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util ...

  4. Docker 容器内配置Tomcat manager 远程控制

    下载tomcat镜像  , docker run it docker exec -ti 容器ID /bin/bash 进入容器 apt-get update ,  apt-get install vi ...

  5. response.setHeader()用法

    response.setHeader()下载中文文件名乱码问题 收藏  1. HTTP消息头 (1)通用信息头 即能用于请求消息中,也能用于响应信息中,但与被传输的实体内容没有关系的信息头,如Data ...

  6. 一些C语言里面的编程

    C语言的知识还是不要忘的好: 1.求最大公约数的函数: #include <stdio.h> #define min(a,b) (a)>(b)?(b):(a) int gcd(int ...

  7. 【转】XGBoost 与 Boosted Tree

    XGBoost 与 Boosted Tree http://www.52cs.org/?p=429 作者:陈天奇,毕业于上海交通大学ACM班,现就读于华盛顿大学,从事大规模机器学习研究. 注解:tru ...

  8. CMD控制台下的JAVAC就是“不是内部或外部命令

    [Path] 添加 %JAVA_HOME%\bin [JAVA_HOME] D:\Program Files\Java\jdk1.7.0_02 [CLASSPATH] .;%JAVA_HOME%\li ...

  9. mongodb停止遇到shutdownServer failed: unauthorized: this command must run from localhost when running db without auth解决方法

    停止mongodb use admin db.shutdownServer(); mongos> db.shutdownServer(); assert failed : unexpected ...

  10. oracle索引-二元高度

    本文转载 作为数据库管理员来说,要在表上建立索引很简单.但是要知道这个索引是否合适.如何优化索引则就具有一定的难度.这项工作也是用来评价一个数据库管理员是否算得上专家的一个重要指标.那么为什么索引优化 ...