在工厂里难免要用到系统控制,这样的控制系统一般称为SFCS,系统控制的原理是把数据都放到数据库里,以后在产品的每一个测试步骤中从数据库里查询此产品的状态(是否在此测试工位能测试,是否已达到最大测试次数等),而一般负责SFCS的同事会给出存储过程或DLL给测试部门调用。下面就谈一下从Python调用存储过程的方法(Windows平台下,有输出参数的存储过程):
存储过程定义基本如下:
ALTER procedure [dbo].[mysp]
@Station varchar(50),
@SN varchar(50),
@Info varchar(500) output,
@Msg varchar(500) output
1. 使用adodbapi
from adodbapi import connect
server = 'dbserver' user = 'username' password = 'password' database = 'database' sp = 'sp' station = 'station' sn = 'sn'
try: db = connect('Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;\ User ID=%s;Password=%s;'%(server, database, user, password)) except Exception, e: print e else: cur = db.cursor() msg = cur.callproc(sp, (station, sn)) #参数与存储过程有关 if len(msg) > 1: if msg[-1] is None: print 'sn is ok. Can be test at this station' else: print msg[-1] finally: try: db.close() except: pass
|
2. 使用pymssql
from pymssql import connect
server = 'dbserver' user = 'user' password = 'password' database = 'database' sp = 'sp' station = 'station' sn = 'sn'
sql = ['set nocount on'] sql.append('declare @Msg varchar(500)') sql.append('declare @return_value varchar') sql.append("exec @return_value = %s @Station = '%s', @SN = '%s', @Info = , @Msg = @Msg output") sql.append('select @Msg, @return_value') sql = '\n'.join(sql) % (sp, station, sn)
def ffchk(server, user, password, database, sql): try: db = connect(host = server, database = database, user = user, password = password, login_timeout = 10) cur = db.cursor() cur.execute(sql) except Exception, e: print e else: cur.nextset() # 要加上这句才能通过fetch函数取到值 print cur.fetchone() finally: try: db.close() except: pass
|
总结:
1. adodbapi简单,不用写一串的sql语句,但是不能取到返回的Error Code,只能取到返回的错误信息,也可能是我没找到方法
2. pymssql与第一条相反,可以取到返回值和错误信息,但要写sql语句。
阅读(692) | 评论(0) | 转发(0) |