python excel导入到数据库

时间:2022-10-20 12:35:51
import xlrd
import MySQLdb
def inMySQL(file_name):
    wb = xlrd.open_workbook(file_name)
    sh = wb.sheet_by_index(0)
    data = [sh.row_values(row) for row in range(0,sh.nrows)]

    db = MySQLdb.connect("localhost","root","123","STUDENTS",use_unicode=1, charset='utf8')
    cursor = db.cursor()

    sql ='''INSERT INTO students VALUES(%s,%s,%s,%s,%s,%s)'''

    cursor.executemany(sql,data)
    db.commit()
    cursor.close()
    db.close()
if __name__=="__main__":
    inMySQL('/home/wangzhch/test.xls')