Python database connection
In python is it possible to add connection timeout in the below code,if possible then please help me
connectionString = "Provider=S开发者_开发知识库QLOLEDB.1;Data Source="+options.server+";Initial Catalog="+options.database+";Integrated Security=SSPI"
Connection = win32com.client.Dispatch('ADODB.Recordset')
Connection.ActiveConnection = connectionString
Connection.ActiveConnection.CommandTimeout = 3600
Read a generic example here: http://programming-guides.com/python/timeout-a-function
I think you have to actively create (and open) the connection:
conn = win32com.client.Dispatch('ADODB.Connection')
conn.CommandTimeout = 3600
conn.Open(connection_string)
And then you can do stuff like:
rs = win32com.client.Dispatch('ADODB.RecordSet')
rs.Open(qry, conn)
(I guess you can also set the ActiveConnection
and CommandText
etc... of the recordset and then execute, but I always thought Open()
was the easier way, and my knowledge of the api is rusty to say the least...)
Personally, I find it easier to use a module that follows the standard Python db api, such as adodbapi (included with pywin32, which you are already using), which also uses the COM api, but takes care of that "under the hood", or pyodbc.
Example with adodbapi:
conn = adodbapi.connect(conn_string, timeout=3600)
cur = conn.cursor()
cur.execute(qry)
And a final tip: have a look at sqlalchemy which makes things even easier (even if you're not using the other stuff like the ORM)
精彩评论