python数据库操作常用功能使用详解(创建表/插入数据/获取数据)

yipeiwu_com6年前Python基础

实例1、取得MYSQL版本

复制代码 代码如下:

# -*- coding: UTF-8 -*-
#安装MYSQL DB for python
import MySQLdb as mdb
con = None
try:
    #连接mysql的方法:connect('ip','user','password','dbname')
    con = mdb.connect('localhost', 'root',
        'root', 'test');
    #所有的查询,都在连接con的一个模块cursor上面运行的
    cur = con.cursor()
    #执行一个查询
    cur.execute("SELECT VERSION()")
    #取得上个查询的结果,是单个结果
    data = cur.fetchone()
    print "Database version : %s " % data
finally:
    if con:
        #无论如何,连接记得关闭
        con.close()

执行结果:
Database version : 5.5.25

实例2、创建一个表并且插入数据

复制代码 代码如下:

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
#将con设定为全局连接
con = mdb.connect('localhost', 'root', 'root', 'test');
with con:
    #获取连接的cursor,只有获取了cursor,我们才能进行各种操作
    cur = con.cursor()
    #创建一个数据表 writers(id,name)
    cur.execute("CREATE TABLE IF NOT EXISTS \
        Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
    #以下插入了5条数据
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")

实例3、python使用slect获取mysql的数据并遍历

复制代码 代码如下:

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
#连接mysql,获取连接的对象
con = mdb.connect('localhost', 'root', 'root', 'test');
with con:
    #仍然是,第一步要获取连接的cursor对象,用于执行查询
    cur = con.cursor()
    #类似于其他语言的query函数,execute是python中的执行查询函数
    cur.execute("SELECT * FROM Writers")
    #使用fetchall函数,将结果集(多维元组)存入rows里面
    rows = cur.fetchall()
    #依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示
    for row in rows:
        print row

复制代码 代码如下:

执行结果:
(1L, ‘Jack London')
(2L, ‘Honore de Balzac')
(3L, ‘Lion Feuchtwanger')
(4L, ‘Emile Zola')
(5L, ‘Truman Capote')

实例4、使用字典cursor取得结果集(可以使用表字段名字访问值)

复制代码 代码如下:

# -*- coding: UTF-8 -*-
# 来源:疯狂的蚂蚁的博客www.server110.com总结整理
import MySQLdb as mdb
import sys
#获得mysql查询的链接对象
con = mdb.connect('localhost', 'root', 'root', 'test')
with con:
    #获取连接上的字典cursor,注意获取的方法,
    #每一个cursor其实都是cursor的子类
    cur = con.cursor(mdb.cursors.DictCursor)
    #执行语句不变
    cur.execute("SELECT * FROM Writers")
    #获取数据方法不变
    rows = cur.fetchall()
    #遍历数据也不变(比上一个更直接一点)
    for row in rows:
        #这里,可以使用键值对的方法,由键名字来获取数据
        print "%s %s" % (row["Id"], row["Name"])

实例5、获取单个表的字段名和信息的方法

复制代码 代码如下:

# -*- coding: UTF-8 -*-
# 来源:疯狂的蚂蚁的博客www.server110.com总结整理
import MySQLdb as mdb
import sys
#获取数据库的链接对象
con = mdb.connect('localhost', 'root', 'root', 'test')
with con:
    #获取普通的查询cursor
    cur = con.cursor()
    cur.execute("SELECT * FROM Writers")
    rows = cur.fetchall()
    #获取连接对象的描述信息
    desc = cur.description
    print 'cur.description:',desc
    #打印表头,就是字段名字
    print "%s %3s" % (desc[0][0], desc[1][0])
    for row in rows:
        #打印结果
        print "%2s %3s" % row

复制代码 代码如下:

运行结果: cur.description: ((‘Id', 3, 1, 11, 11, 0, 0), (‘Name', 253, 17, 25, 25, 0, 1))
Id Name
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote


实例6、使用Prepared statements执行查询(更安全方便)

复制代码 代码如下:

# -*- coding: UTF-8 -*-
# 来源:疯狂的蚂蚁的博客www.server110.com总结整理
import MySQLdb as mdb
import sys
con = mdb.connect('localhost', 'root', 'root', 'test')
with con:
    cur = con.cursor()
    #我们看到,这里可以通过写一个可以组装的sql语句来进行
    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s",
        ("Guy de Maupasant", "4"))
    #使用cur.rowcount获取影响了多少行
    print "Number of rows updated: %d" % cur.rowcount

结果:
复制代码 代码如下:

Number of rows updated: 1

相关文章

python常见字符串处理函数与用法汇总

本文实例讲述了python常见字符串处理函数与用法。分享给大家供大家参考,具体如下: 1、find 作用:在一个较长字符串中查找子串。返回子串所在位置的最左端索引,如果没有找到则返回-...

在Python的web框架中中编写日志列表的教程

在Python的web框架中中编写日志列表的教程

MVVM模式不但可用于Form表单,在复杂的管理页面中也能大显身手。例如,分页显示Blog的功能,我们先把后端代码写出来: 在apis.py中定义一个Page类用于存储分页信息: c...

Python 3.6打包成EXE可执行程序的实现

Python 3.6打包成EXE可执行程序的实现

1、下载pyinstaller python 3.6 已经自己安装了pip,所以只需要执行 pip install pyinstaller就可以了 2、打包程序 进入到你你需要打包的目...

详解python:time模块用法

详解python:time模块用法

time模块下有两种时间表示方法: 第1种是:时间戳的方式。是基于1970年1月1日0时0分0秒的偏移。浮点数。 第2种是:struct_time()类型的表示方法。gmtime()和l...

pygame实现成语填空游戏

pygame实现成语填空游戏

最近看到很多人玩成语填字游戏,那么先用pygame来做一个吧,花了大半天终于完成了,附下效果图。 偷了下懒程序没有拆分,所有程序写在一个文件里,主要代码如下: # -*- codi...