1. 程式人生 > >SQL Server:過程 請求失敗,因為 是表物件

SQL Server:過程 請求失敗,因為 是表物件

首先import win32com.client #匯入com相關的庫

使用Python連線SQL Server 2005資料庫時出現了以下問題:

rs = win32com.client.Dispatch(r'ADODB.Recordset') 

rs.Open('[sometable]', conn, 1, 3) 

有時候正常

有時候出現異常,提示:過程'sometable' 的請求失敗,因為 'sometable' 是 表 物件。

按異常說明好像是把sometable當成過程來處理了,可這裡是一個表名啊

網上搜索半天,未果

檢視ADO幫助文件,發現recordset.Open 有5個引數

recordset.Open Source, ActiveConnection, CursorType, LockType, Options

其中第5個引數Options的說明如下:

Optional. A Long value that indicates how the provider should evaluate the Source argument if it represents something other than a Command object, or that the Recordset should be restored from a file where it was previously saved. Can be one or more CommandTypeEnum or ExecuteOptionEnum values, which can be combined with a bitwise OR operator.

大體就是說與Source引數有關,如何解釋Source的意思

有如下幾個定義

adCmdUnspecified  -1  Does not specify the command type argument.

adCmdText  1  Evaluates CommandText as a textual definition of a command or stored procedure call.

adCmdTable  2  Evaluates CommandText as a table name whose columns are all returned by an internally generated SQL query.

 adCmdStoredProc  4  Evaluates CommandText as a stored procedure name.

adCmdUnknown  8  Default. Indicates that the type of command in the CommandText property is not known.

adCmdFile  256  Evaluates CommandText as the file name of a persistently stored Recordset. Used with Recordset.Open or Requery only.

adCmdTableDirect  512  Evaluates CommandText as a table name whose columns are all returned. Used with Recordset.Open or Requery only. To use the Seek method, the Recordset must be opened with adCmdTableDirect.This value cannot be combined with the ExecuteOptionEnum value adAsyncExecute.

可以解釋Source的含義,adCmdTable是讓底下把Source當tablename解釋

所以改成

rs = win32com.client.Dispatch(r'ADODB.Recordset') 

rs.Open('[sometable]', conn, 1, 3, 2) 

問題解決

win32com.client是安裝PythonWin後的庫,網址http://starship.python.net/crew/mhammond/win32/