1.使用Pandas写入MSSQL
def sql(host, db, user, pwd):
print('开始连接数据库....')
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s" % (host, db, user, pwd))
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
engine.connect()
print('数据库连接成功')
df.to_sql('testlx', con=engine, if_exists='append', index=False,chunksize=1000000)
特别注意
df.to_sql('testlx', con=engine, if_exists='append', index=False,chunksize=1000000)
中的 if_exists='',如果使用replace,将会修改数据库表的字段名称;如果使用append,如果xls文件列数大于数据库表的字段数,将不能导入。
2. cursor.fetchall() 只能调用一次,调用后fetchall()此值将被清空!!切记
我在调试写入mssql,老是发现写入是没有数据,查资料也没有找到原因,最终发现我想看cursor.fetchall() 返回了什么数据,在语句里面增加了一行
print(cursor.fetchall())
conn = pymssql.connect(hostH, userH, pwdH, dbH)
cursor = conn.cursor()
ml = "select 医保护士代码 from hs where 医保护士代码='" + record_no + "'"
p_ml = cursor.execute(ml)
print(cursor.fetchall())
if cursor.fetchall(): #有数据
print('【', record_no,record_name, record_sfzh.strip(),'】\033[34m的医保注册信息已存在系统里,跳过……\033[0m')
else:
cursor.executemany(
"INSERT INTO gb_ry_hs(医保护士代码,姓名执业类别,专业技术职务) VALUES(%s,%s,%s)",
articledata[no1:no1 + 1])
conn.commit()
conn.close()
结果一直if判断语言一直不起作用,删除此语句后正常!
conn = pymssql.connect(hostH, userH, pwdH, dbH)
cursor = conn.cursor()
ml = "select 医保护士代码 from hs where 医保护士代码='" + record_no + "'"
p_ml = cursor.execute(ml)
if cursor.fetchall(): #有数据
print('【', record_no,record_name, record_sfzh.strip(),'】\033[34m的医保注册信息已存在系统里,跳过……\033[0m')
else:
cursor.executemany(
"INSERT INTO gb_ry_hs(医保护士代码,姓名执业类别,专业技术职务) VALUES(%s,%s,%s)",
articledata[no1:no1 + 1])
conn.commit()
conn.close()