1,环境准备
Python的MySQL数据库操作模块叫MySQLdb
自己百度安装方法(pip install MySQLdb)
可以选择一种方法: from MySQLdb import connect
from mysql.connector import connect
root@template liguang]# mysql -uroot -p123456 一台装有mysql的服务器
>>>
>>> import MySQLdb #导入MySQLdb 模块(实际上用的是MySQLdb里面得connect模块)
>>>
>>> conn = MySQLdb.Connect(host='localhost',user='root',passwd='123456',db='test',charset='utf8')#与数据库建立连接
>>>
>>> cursor = conn.cursor()#创建一个游标对象
>>>
>>> sql = "create table user(id int,name varchar(30),password varchar(30))"#sql语句
>>>
>>> cursor.execute(sql)#执行sql语句
0L
>>> sql = "insert into user(id,name,password) values('1','xiaoming','111111')"
>>>
>>> cursor.execute(sql)#执行sql语句
1L
>>>
>>> conn.commit()
# 提交事务,写入到数据库
>>>
>>> cursor.execute('show tables')#查看创建的表
2L
>>> cursor.fetchall()#返回上一个游标执行的所有结果,默认是以元组形式返回
((u'teacher',), (u'user',))
>>>
>>> cursor.execute('select * from user')#
1L
>>>
>>> cursor.fetchall()
#返回上一个游标执行的所有结果,默认是以元组形式返回
((1L, u'xiaoming', u'111111'),)
>>>
-----------------插入多条数据:
>>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'
>>>
>>>
>>> args = [('2','zhangsan','123456'),('3','liguang','123456')]
>>>
>>> cursor.executemany(sql,args)
2L
>>> conn.commit()
>>>
>>> sql = 'select * from user'
>>>
>>> cursor.execute(sql)
3L
>>>
>>> cursor.fetchall()
((1L, u'xiaoming', u'111111'), (2L, u'zhangsan', u'123456'), (3L, u'liguang', u'123456'))
>>>
>>>
-------------------------------------以字典形式返回结果:
默认显示的是元祖形式,要想返回字典形式,使得更易处理,就要用到cursor([cursorclass])中的cursorclass参数。
传入MySQLdb.cursors.DictCursor类:
如:
>>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)
>>>
>>> sql = 'select * from user'
>>>
>>> cursor.execute(sql)
3L
>>>
>>> cursor.fetchall()
({'password': u'111111', 'id': 1L, 'name': u'xiaoming'}, {'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'liguang'})
>>>
遍历查询结果:
1 # /usr/bin/env python
2 #-*- coding:utf-8 -*-
3 import MySQLdb
4 try:
5 conn = MySQLdb.Connect(host='localhost',user='root',passwd='123456',connect_timeout=3,db='test',charset='utf8')
6 cursor = conn.cursor()
7 sql = "select * from user"
8 cursor.execute(sql)
9 for i in cursor.fetchall():
10 print i
11 except Exception,e:
12 print ("Connection Error:"+str(e))
13 finally:
14 conn.close()
[root@template liguang]# python con_database.py
(1L, u'xiaoming', u'111111')
(2L, u'zhangsan', u'123456')
(3L, u'liguang', u'123456')
------------------------------------------------------------------------------------------------------------------------------------------------
python数据库游标对象详解:
python开发的MySQLdb遵从DB-API,实现了connect(),connect.cursor()等方法。。其他db类也实现了同样的方法,故可以很容易移植
DB-API规范的属性:
apilevel DB_API模块兼容的DB-API版本号
threadsafety 线程安全级别
paramstyle改模块支持的SQL语句参数风格
DB-API规范的方法:
connect()连接函数,生成一个connect对象,以提供数据库操作,同时函数参数也是固定好的
其中connect对象又有如下方法:
#所谓事务可以认为是一整套操作 只要有一处纰漏就废
close():关闭此connect对象,关闭后无法再进行操作,除非再次创建连接
commit():提交当前事务,如果是支持事务的数据库执行增删改查后没有commit则数据库默认回滚,白操作了
rollback():取消当前事务
cursor():创建游标对象
其中游标对象又有如下属性和方法:
常用方法:
close():关闭此游标对象
fetchone():得到结果集的下一行
fetchmany([size = cursor.arraysize]):得到结果集的下几行
常用属性:
connection:创建此游标对象的数据库连接