python - 将数据从 Excel 导入到 Mysql Python

标签 python mysql excel

这段代码适用于字符串,但 float 列在数据库中不一样,我不明白它是如何工作的,例如在Excel文件中,数据库“254.0835”中的值“215,325”,还有许多其他值已更改。

import MySQLdb
import xlrd

list= xlrd.open_workbook("prod.xls")
sheet= list.sheet_by_index(0)

database = MySQLdb.connect (host="localhost" , user="root" , passwd="" ,db="table")
cursor = database.cursor()

query= """INSERT INTO produits (idProduit, idCategorie, LibelleProduit, PrixProduit) VALUES (%s, %s, %s, %s)"""



for r in range(1,sheet.nrows):
    idProduit = sheet.cell(r,0).value
    categorie = 999
    libelle=sheet.cell(r,1).value
    prix=sheet.cell(r,3).value #>>>>> HERE THE PROBLEM the Imported Value <<<<


    values = (idProduit,categorie,libelle,prix)

    cursor.execute(query,values)



cursor.close();
database.commit()

database.close()

print""
print "All done !"

columns= str(sheet.ncols)
rows=str(sheet.nrows)
print "i just import "+columns+" columns and " +rows+ " rows to MySQL DB"

另外,我尝试将 SQL 类型更改为 Varchar,它也已更改。

最佳答案

从 Excel 读取数据时出现此问题。如果你知道它的 float 据,那么你可以在将其插入 MySQL 之前清理它。

import re
prix=sheet.cell(r,3).value
prix = str(prix)
prix = re.sub('[^0-9.]+', '', prix )
print float(prix)

这样只有数字和。将保留所有其他垃圾将被丢弃。

import MySQLdb
import re
database = MySQLdb.connect (host="localhost" , user="test" , passwd="" ,db="test")
cursor = database.cursor()
query= """INSERT INTO test (id, num) VALUES (%s, %s)"""

prix = "215,325"
prix = str(prix)
prix = re.sub('[^0-9.]+', '', prix )
prix = float(prix)
values = (23,prix)

cursor.execute(query,values)
cursor.close();
database.commit()
database.close()
print "Done"

关于python - 将数据从 Excel 导入到 Mysql Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28540629/

相关文章:

MySQL数据类型困惑。在手册中它说 "but should be no greater than M−2."

PHPExcel 设置 setRowHeight(-1) 和 setWrapText(true) 不会自动调整行的高度

excel - 阻止 Excel 将字符串转换为数字

Excel VBA - 错误 1004

python - MySQLdb/_mysql.c(29) : fatal error C1083: Cannot open include file: 'mysql.h' : No such file or directory

python - django 在 Raspberry PI 中使用热敏打印机

python - Django : How can I implement a remember me key on my login page

python - 根据 "not in"条件从数据帧中删除行

mysql - FastAPI:mysql自动创建表的问题

mysql - 这是MariaDB中ROUND函数的故障吗?