python DB-API

python为数据库访问开发了统一的API(Application Programming Interface,应用程序编程接口):DB-API.python

MySQL的实现叫作MySQLdb,Oracle实现为Oracledb。数据库

每一个模块都包含一个connect()方法,它返回一个DB-API链接对象。编程

一、链接对象的API:  下面例子使用用户名/口令链接本地主机(localhost)上的MySQL数据库test.fetch

>>> import  MySQLdbspa

>>> conn = MySQLdb.connect(host='localhost', user='root',passwd='123456', db='test');对象

二、链接对象经过cursor()方法为应用提供一个游标:接口

cursor = conn.cursor()开发

游标是数据库访问的中心。经过execute()方法,能够向数据库发送SQL并处理任何结果。get

例如1:使用MySQL链接所生成的游标向数据库插入了一个新行,而后经过输出受影响行的数目来验证插入。对于插入,这个值应当总为1.it

>>> cursor.execute("INSERT test VALUES(5, 'test')");
1L

>>> print 'Affected rows: ', cursor.rowcount;
Affected rows: 1

例2:查询处理,使用execute()方法向数据库发送SQL.

>>> cursor.execute("SELECT id, username FROM test ORDER BY id");
4L
>>> for row in cursor.fetchall():   #游标对象提供的获取方法:fetchone()(返回一行元组,其中每一个元素表示返回行中的一列), fetchmany()(处于fetchone()与fetchall()之间), fetchall()(从查询中获取全部结果,放在python元组列表中)
... print 'key: ', row[0];
... print 'value: ', row[1];
...
key: 1
value: John
key: 2
value: Mary
key: 9
value: Rose
key: 10
value: Hello

完成相应的操做后关闭链接:

>>> conn.close();

三、参数化SQL

参数化SQL是带有占位符的SQL语句,能够向其传递参数

cursor.execute( 'INSERT colors(cour, abbr) VALUES(%s, %s )', ('blue', 'bl') );

使用cursor.execute()一次只能插入一条记录,使用cursor.executemany()能够插入多条:

cursor.executemany("INSERT colors(cour, abbr) VALUES(%s, %s)", (('blue', 'bl'), ('purple', 'ppl'), ('orange', 'orn') ) );

相关文章
相关标签/搜索