1
存儲過程我有一個Python腳本,定期查詢數據(使用SQLAlchemy的0.7.4)MySQL數據庫。它通過運行存儲過程來實現。如果過程返回任何內容,腳本將嘗試處理數據(這部分與數據塊無關),然後使用第二個過程保存結果。蟒蛇+ SQLAlchemy的:調用循環
這將睡在一定時間(通常爲一分鐘),並給它的所有又一次,直到停止後。它應該能夠運行數週。
我會經常收到此錯誤:「無法重新連接,直到無效的事務回滾」。我做了使用各種信息的一些變化,我可以找到這一點,我想知道這是否是我想要的達到的一個好辦法:
from sqlalchemy import create_engine, exc
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text, func
import time
class StoredProcedures():
_engine = None
_connection = None
_session = None
def __init__(self, cs):
self._engine = create_engine(cs, encoding='utf-8', echo=False, pool_recycle=600)
self._connection = self._engine.connect()
Session = sessionmaker(bind=self._engine)
self._session = Session()
def sp_test_1(self, user_id):
t = self._session.begin(subtransactions=True)
try:
query = 'call sp_get_files(%d)'%user_id
result = self._session.execute(query).fetchall()
t.close()
return result
except exc.DBAPIError, e: #Proper way of reconnecting?
t.rollback()
time.sleep(5)
self._connection = self._engine.connect()
Session = sessionmaker(bind=self._engine)
self._session = Session()
except:
t.rollback()
return None
cs = "mysql://test:[email protected]/test_db"
db_stored_procedures = StoredProcedures(cs)
while (True):
files = db_stored_procedures.sp_test_1(1)
if len(files) > 0:
print "This is where processing happens"
#And this is where the second procedure would be called to store the results
time.sleep(15)
我測試了這一點,但我幾乎只寫了所以我沒有做任何長期的測試。我想先徵求你的意見。
編輯: 我原來使用的連接執行查詢,像這樣(省略大部分的腳本是同上一):
def sp_test_1(self, user_id):
t = self._connection.begin()
try:
query = 'call sp_get_files(%d)'%user_id
result = self._connection.execute(query).fetchall()
t.close()
return result
except exc.DBAPIError, e:
#same as above
except:
t.rollback()
return None
我會盡量給你堆棧跟蹤,但這偶爾會發生,我不能總是複製它。我也有存儲過程的另一個問題,但我認爲這更適合一個新的問題。 – gkres 2013-02-19 14:57:00
如果它是零星的,我會花很長時間仔細查看MySQL日誌。 – JosefAssad 2013-02-19 14:59:32