嗨,我有下面的python代码来连接到我的SQL Server DB
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def connect_to_db(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
self.conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
def execute_select_query(self, query):
try:
curr = self.conn.cursor()
out = curr.execute(query).fetchall()
except pyodbc.IntegrityError as e:
out = []
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
out = []
print('ms-sql Operation Error: {0}'.format(err))
except AttributeError as err:
out = []
print('Connection to DB failed')
pass
try:
curr.close()
except:
print('Connection to DB failed')
return out
def execute_inset_query(self, query):
try:
database_cursor = self.conn.cursor()
database_cursor.execute(query)
except pyodbc.DataError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.IntegrityError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
print('ms-sql error: {0}'.format(e))
然后在我的主程序中,我正在尝试这个,它运行得很好,直到我断开网络
DBT = CDBTools("192.168.1.2instance4", "my_db", "my_username", "my_passowrd")
DBT.connect_to_db()
while(True):
print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query("SELECT Name FROM Persons WHERE ID='1'")))
当我断开网络时,我没有得到任何错误,只是时间不再重要(当然是因为查询失败(,但当我重新连接网络时,查询再也不会成功
那么,有人可能知道我如何修改execute_select_query和execute_inset_query吗?这样,当恢复到数据库的连接时,它将重新开始工作:(
感谢的光临和问候
试试这个,它会在每次使用with
子句时连接,并在您离开它时自动断开连接。
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def connect_to_db(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
return conn
def execute_select_query(self, conn, query):
try:
curr = conn.cursor()
out = curr.execute(query).fetchall()
except pyodbc.IntegrityError as e:
out = []
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
out = []
print('ms-sql Operation Error: {0}'.format(err))
except AttributeError as err:
out = []
print('Connection to DB failed')
pass
def execute_inset_query(self, conn, query):
try:
database_cursor = conn.cursor()
database_cursor.execute(query)
except pyodbc.DataError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.IntegrityError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
print('ms-sql error: {0}'.format(e))
然后:
DBT = CDBTools("192.168.1.2instance4", "my_db", "my_username", "my_passowrd")
while True:
with DBT.connect_to_db() as conn:
print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query(conn, "SELECT Name FROM Persons WHERE ID='1'")))
我可能会制作一个方法来返回光标,而不是连接。例如:
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def get_cursor(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
return conn.cursor()
DBT = CDBTools("192.168.1.2instance4", "my_db", "my_username", "my_passowrd")
with DBT.get_cursor() as cursor:
cursor.execute("SELECT Name FROM Persons WHERE ID='1'")
for row in cursor.fetchall():
print(row)
祝你好运!