写一个函数,保存Pandas表格数据到SQL数据库的一个新表中。
函数有两个参数:data
是要保存的表格,table_name
是要新建的数据库表。
def pdtosql(data,table_name):
a=b= ''
for each in data.columns:
a = a + each + " " + 'varchar(255)'+','
b = b + each + " " + ','
a = a[:-1]
b = b[:-1]
c = str('%s,'*len(data.columns))[:-1]
#新建table
with conn.cursor() as cursor:
cursor.execute("DROP TABLE IF EXISTS {}".format(table_name)) # 如果存在,删除同名table
sql = '''
create table {} (
{}
) engine=innodb default charset=utf8
'''.format(table_name,a)
cursor.execute(sql)
print('Table "{}" created!'.format(table_name))
#插入数据
#values = [tuple(each) for each in data.values]
values= [[item if item == item else None for item in each] for each in data.values]
with conn.cursor() as cursor:
sql = "INSERT INTO {} ({}) VALUES ({})".format(table_name,b,c)
cursor.executemany(sql,values)
conn.commit()
print("Data insert done!")