Python例程:使用adodbapi访问MSSQL数据库
来源:互联网 发布:我的青春恋爱物语知乎 编辑:程序博客网 时间:2024/03/29 18:21
今天学习用Python访问数据库,以前用ADO习惯了,所以先找个封装了ADO的模块来试试。
adodbapi是用python封装ADO的数据库访问模块,adodbapi接口完全符合Python DB-API2.0规范,简单易用。
以下是自己学习过程中写的一个例程,使用了查询、建表、插入数据、执行存储过程等功能,基本上涵盖了日常数据库编程所需的功能。
#coding=utf-8
import adodbapi
class DBTestor:
def __init__(self):
self.conn = None
def __del__(self):
try:
self.conn.close()
except:
pass
def connectDB(self, connectString):
self.conn = adodbapi.connect(connectString)
def closeDB(self):
self.conn.close()
def fielddict(self, cursor):
dict = {}
i = 0
for field in cursor.description:
dict[field[0]] = i
i += 1
return dict
def testCommand(self):
u"测试执行SQL命令,及参数、事务"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'Demo_Table') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Drop Table Demo_Table;
CREATE TABLE Demo_Table (
ID int IDENTITY (1, 1) NOT NULL ,
Name varchar(50) NOT NULL Default('')
PRIMARY KEY CLUSTERED
(
[ID ]
)
);"""
cursor.execute(sql)
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame",))
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame2",))
sql = """SELECT @@Identity;"""
cursor.execute(sql)
print "Inserted new record's ID = %s" % cursor.fetchone()[0]
cursor.close()
#默认对数据库进行修改后必须要提交事务,否则关闭数据库时会回滚
self.conn.commit()
def testQuery(self):
u"测试查询功能,通过序号和字段名读取数据"
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM authors")
try:
fields = self.fielddict(cursor)
row = cursor.fetchone()
while row != None:
print "%s: %s %s" % (row[0], row[fields['au_fname']], row[fields['au_fname']])
row = cursor.fetchone()
finally:
cursor.close()
def testStoreProc(self):
u"测试存储过程功能"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'insert_data_demo') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
Drop Procedure insert_data_demo;"""
cursor.execute(sql)
sql = """CREATE PROCEDURE INSERT_DATA_Demo
@Name varchar(50),
@ID int output
AS
INSERT INTO Demo_Table (Name) VALUES (@Name);
Select @ID = @@Identity;"""
cursor.execute(sql)
(name, id) = cursor.callproc("insert_data_demo", ("tom", 0))
print "Inserted new record's ID = %i" % id
sql = """SELECT * FROM Demo_Table;"""
cursor.execute(sql)
print cursor.fetchall()
cursor.close()
self.conn.commit()
if __name__ == "__main__":
test = DBTestor()
test.connectDB("Provider=SQLOLEDB.1;Persist Security Info=True;Password=;User ID=sa;Initial Catalog=pubs;Data Source=.")
try:
test.testQuery()
test.testCommand()
test.testStoreProc()
finally:
test.closeDB()
import adodbapi
class DBTestor:
def __init__(self):
self.conn = None
def __del__(self):
try:
self.conn.close()
except:
pass
def connectDB(self, connectString):
self.conn = adodbapi.connect(connectString)
def closeDB(self):
self.conn.close()
def fielddict(self, cursor):
dict = {}
i = 0
for field in cursor.description:
dict[field[0]] = i
i += 1
return dict
def testCommand(self):
u"测试执行SQL命令,及参数、事务"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'Demo_Table') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Drop Table Demo_Table;
CREATE TABLE Demo_Table (
ID int IDENTITY (1, 1) NOT NULL ,
Name varchar(50) NOT NULL Default('')
PRIMARY KEY CLUSTERED
(
[ID ]
)
);"""
cursor.execute(sql)
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame",))
sql = """INSERT INTO Demo_Table (Name) VALUES (?);"""
cursor.execute(sql, ("jame2",))
sql = """SELECT @@Identity;"""
cursor.execute(sql)
print "Inserted new record's ID = %s" % cursor.fetchone()[0]
cursor.close()
#默认对数据库进行修改后必须要提交事务,否则关闭数据库时会回滚
self.conn.commit()
def testQuery(self):
u"测试查询功能,通过序号和字段名读取数据"
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM authors")
try:
fields = self.fielddict(cursor)
row = cursor.fetchone()
while row != None:
print "%s: %s %s" % (row[0], row[fields['au_fname']], row[fields['au_fname']])
row = cursor.fetchone()
finally:
cursor.close()
def testStoreProc(self):
u"测试存储过程功能"
cursor = self.conn.cursor()
sql = """if exists (select * from sysobjects where id = object_id(N'insert_data_demo') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
Drop Procedure insert_data_demo;"""
cursor.execute(sql)
sql = """CREATE PROCEDURE INSERT_DATA_Demo
@Name varchar(50),
@ID int output
AS
INSERT INTO Demo_Table (Name) VALUES (@Name);
Select @ID = @@Identity;"""
cursor.execute(sql)
(name, id) = cursor.callproc("insert_data_demo", ("tom", 0))
print "Inserted new record's ID = %i" % id
sql = """SELECT * FROM Demo_Table;"""
cursor.execute(sql)
print cursor.fetchall()
cursor.close()
self.conn.commit()
if __name__ == "__main__":
test = DBTestor()
test.connectDB("Provider=SQLOLEDB.1;Persist Security Info=True;Password=;User ID=sa;Initial Catalog=pubs;Data Source=.")
try:
test.testQuery()
test.testCommand()
test.testStoreProc()
finally:
test.closeDB()
程序说明:
1. 因为源代码有中文,所以要在第一行加上 #coding=utf-8
2. adodbapi默认在Connection的__init__里面开启事务BeginTrans(),然后在close方法里面回滚事务RollbackTrans()。因此对数据库进行修改之后要调用Connection.commit()提交事务才会保存数据。这一点与ADO的默认行为不一致,需要注意。
3. cursor.fetch*()方法返回的是tuple,只能通过序号读取字段值,如果要通过字段名访问数据,需要将字段名映射为序号。测试代码里面的fielddict方法利用cursor.description属性实现了此映射过程。
总结:
感觉Python DB-API2.0接口使用是很简单和方便的,只不过接口功能稍弱了点,比如没有MoveFirst等功能,不能多次遍历单个结果记录集,而且不直接支持使用字段名访问数据,需要做转换。
参考资料:
1. PEP-0249, Python Database API Specification V 2.0
2. adodbapi 官方网站
3. 数据库连接字符串大全
- Python例程:使用adodbapi访问MSSQL数据库
- Python例程:使用adodbapi存取二进制数据
- 使用PHP访问MSSQL SERVER数据库小结
- python 使用 adodbapi 连接mssql2005的连接字符串
- python访问MsSql
- MyEclipse使用SQL Explorer访问MSSQL命名实例数据库
- MSsql 数据库服务器不能访问
- [MSSQL]跨数据库访问数据表
- 利用Javabean访问MSSQL数据库
- 利用servlet访问MSSQL数据库
- 利用Javabean访问MSSQL数据库
- python 使用pymssql 连接MSSQL数据库(带端口)
- 菜鸟学Python(17):用pymssql访问mssql数据库的存储过程
- 一个简单访问Mysql数据库的例程
- opencv python接口 像素访问例程
- 如何在ORACLE数据库访问MSSQL
- 图文详解Silverlight访问MSSQL数据库
- PHP访问数据库代码(MSSQL版)
- c#委托和事件
- 批量替換
- sql数据库修复技术
- C#的New关键字有几种用法
- live不是万能的
- Python例程:使用adodbapi访问MSSQL数据库
- Python例程:使用adodbapi存取二进制数据
- CSDN博客如何添加友情链接的方法
- 一则笑话
- 在Appengine中使用AMF通信
- Appengine中的JSON序列化
- 上下文绑定对象之一(定义)
- Windows运行命令集锦
- Java编程那些事儿73——JDK文档使用