Python自定义类连接数据库
利用之前unixODBC配置的数据源,自定义一个类然后连接数据库
import pyodbc
class DB18:
def __init__(self):
self.conn = self.open()
if self.conn:
self.cr = self.conn.cursor()
def open(self):
try:
cnxn=pyodbc.connect("DSN=200;PWD=test1234")
cnxn.setdecoding(pyodbc.SQL_WCHAR, encoding='GBK')
cnxn.setdecoding(pyodbc.SQL_CHAR, encoding='GBK')
cnxn.setencoding(encoding='GBK')
except:
print("数据库连接失败!请联系路保辉.")
else:
return cnxn
def close(self):
try:
self.conn.close()
except:
raise("关闭异常")
使用pandas read_sql读取数据到DataFrame
import pandas as pd
db = DB18()
mycon = db.conn
stmt = 'select first 10 * from bftj where date=today-1'
df = pd.read_sql(stmt,mycon,index_col=['date'])