代码如下:
import pymssql #安装pymssql包 server="210.77.77.237:49391" #定义连接服务地址 user="用户名" #用户名 password="密码" #密码 database="数据库名" #数据库名 conn = pymssql.connect(server, user, password, database) #创建连接对象 cursor = conn.cursor() #用连接对象创建连接线程 class LogDB: #定义一个类 def __enter__(self): #类加载时会自动运行该代码 print("进来了") LogDB().SelectTable(); #调用方法 return self def SelectTable(self): print("运行了") self.sql = "SELECT * FROM [geoAI.EP.MonitorStation].[dbo].[RS_Disaster]" #建立sql cursor.execute(self.sql) #利用线程运行sql self.row = cursor.fetchone() #拿到sql执行后得到的结果 for self.row in cursor: #遍历对象 print("ID=%d, Time=%s,Name=%r" % (self.row[0], self.row[1], self.row[6])) def __exit__(self, exc_type, exc_val, exc_tb): #该类退出时自动执行exit方法里的代码 cursor.close() #关闭线程 conn.close() #关闭连接 print("退出了") with LogDB() as db: print("hello")运行结果:
进来了 运行了 ID=143692300389286032181738833738908229083, Time=2017-09-06 00:00:00,Name=‘Name’ ID=338708972602592704725705783910645060468, Time=2017-09-06 00:00:00,Name=‘Name’ ID=122769569291759861220972900536298866395, Time=2017-09-06 00:00:00,Name=‘Name’ ID=43668803528897560601404296451661636033, Time=2017-09-06 00:00:00,Name=‘Name’ ID=77542279423681989881811435130658268073, Time=2017-09-06 00:00:00,Name=‘Name’ hello 退出了