python DB-API

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

MySQL的实现叫做MySQLdb,Oracle实现为Oracledb。

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

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

>>> import  MySQLdb

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

2、连接对象通过cursor()方法为应用提供一个游标:

cursor = conn.cursor()

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

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

>>> 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();

3、参数化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') ) );

 

posted @ 2017-04-02 11:38  浅色夏沫  阅读(372)  评论(0编辑  收藏  举报