1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import pymssql class ConnectSqlserver(): def __init__(self, host="localhost", user="root", password="", db="test", charset='utf8'): self.conn = pymssql.connect(host=host, user=user, password=password, database=db, charset=charset) self.cursor = self.conn.cursor() def __del__(self): self.conn.close() def run_sql(self, sql): print(sql) try: self.cursor.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print('Error: ', e) finally: pass def get_data(self, sql): print(sql) try: self.cursor.execute(sql) return self.cursor.fetchall() except Exception as e: print('Error: ', e) finally: pass if __name__ == '__main__': conn = ConnectSqlserver(host='localhost', user="username", password="password", db="databasename") sql = 'SELECT * FROM DATA1' data = conn.get_data(sql) print(data[-1][0])
|