时间:2021-07-01 10:21:17 帮助过:2人阅读
2.
import MySQLdb,xlrd,sys db_config={‘user‘:‘root‘,‘passwd‘:‘passwd‘,‘host‘:‘localhost‘,‘db‘:‘test‘,‘port‘:3306} def get_connction(db_config):
‘‘‘
返回数据库的链接,游标信息
‘‘‘ try: conn=MySQLdb.connect(**db_config) cur=conn.cursor() except Exception as e: print ‘Can\‘t Connect the database: ‘,e sys.exit(1) return conn,cur def main(): conn,cur=get_connction(db_config) sql=‘‘‘create table if not exists basic_info (id int primary key not null, name char(20), gender char(2) )‘‘‘ cur.execute(sql) excel=xlrd.open_workbook(r‘D:/data.xls‘) sheet=excel.sheets()[0] nrow=sheet.nrows for row in range(1,nrow): #获取xls每行数据,insert入表,table中id是int型号,填充时也用%s cur.execute(‘insert into basic_info values (%s,%s,%s)‘,tuple(sheet.row_values(row))) conn.commit() cur.close() conn.commit() if __name__==‘__main__‘: main()
xls填充sql
标签: