我有以下熊猫的数据

需要将所有值插入到带有中文字符的数据仓库中,但中文字符被安装为垃圾(?)(百å¨è<±åšï¼ˆèˆŸå±±ï¼‰å·¤é…‘)。œ‰é™…)和上面的查询一样,插入查询是动态准备的。我需要关于如何处理以下场景的帮助:
将文件读入UTF-8,并使用字符集UTF-8使用pyodbc连接写入数据仓库。
df=pd.read_csv(filename,dtype='str',encoding='UTF-8')
cnxn = database_connect() ##Connect to database##
cnxn.setencoding(ctype=pyodbc.SQL_CHAR, encoding='UTF-8')
cnxn.autocommit = True
cursor = cnxn.cursor()
for y in range(len(df)):
inst='insert into '+tablename+' values ('
for x in range(len(clm)):
if str(df.iloc[y,x])=='nan':
df.iloc[y,x]=''
if x!=len(clm)-1:
inst_val=inst_val+"'"+str(df.iloc[y,x]).strip().replace("'",'')+"'"+","
else:
inst_val=inst_val+"'"+str(df.iloc[y,x]).strip().replace("'",'')+"'"+")"
inst=inst+inst_val #########prepare insert statment from values inside in-memory data###########
inst_val=''
print("Inserting value into table")
try:
cursor.execute(inst) ##########Execute insert statement##############
print("1 row inserted")
except Exception as e:
print (inst)
print (e)相同的值应该插入到sql数据仓库中。
发布于 2019-09-01 17:21:34
您正在使用动态SQL构造包含汉字的字符串文字,但您要将它们创建为
insert into tablename values ('你好')当Server期望Unicode字符串文本为窗体时
insert into tablename values (N'你好')最好使用适当的参数化查询来避免这样的问题:
sql = "insert into tablename values (?)"
params = ('你好',)
cursor.execute(sql, params)https://stackoverflow.com/questions/57721682
复制相似问题