使用Python连接SQL Server数据库
import pymssql
#自己设置一下host,user, password, database
conn = pymssql.connect(host=ht,
user=usr,
password=pwd,
database=db,
# charset用UTF-8读中文会乱码,只读英文可以用UTF-8
charset='cp936',
as_dict=False) #有时可以改成True 看情况
cur = conn.cursor()
if not cur:
raise(NameError,"连接数据库失败")
使用Python连接SQL Server数据库执行简单查询SQL语句
结果返回到resList里,再关闭连接
sql = 'SELECT * FROM TABLE1'
cur.execute(sql)
resList = cur.fetchall()
#查询完毕后必须关闭连接
conn.close()
使用Python连接SQL Server数据库执行非查询SQL语句
cur.execute(sql)
conn.commit()
conn.close()
将数据添加到excel
创建excel表并往里添加数据
Judge whether the file exists
if it exists, open the original file,
otherwise create a new file
:param filename: Target file path 目标路径
:param sheet_index: create a new sheet’s index
:param sheet_name: create a new sheet’s name
:param data: 想要添加进的excel数据 (List)
import openpyxl
def write_xlsx(filepath, filename, sheet_index, sheet_name, data):
if os.path.exists(filename):
"the file has already exists"
wb = openpyxl.load_workbook(filename)
else:
"not exists"
wb = openpyxl.Workbook()
#添加sheet在excel里
sheet = wb.create_sheet(title=sheet_name, index=sheet_index)
#添加表头,可视情况修改
sheet.append(['工厂','产品料号','产品类型','子阶料号','Total总量','客户'])
#添加数据进excel表里
for item in data:
sheet.append(item)
#保存
wb.save(filepath+filename)
hint: openpyxl 比 pyxl 可以创建更多的excel行数