将CSV载入数据库无法正常工作

时间:2019-09-21 02:10:30

标签: python mysql csv

所以我正在做Web应用程序,我需要将一个csv文件导出到数据库。 这是我的代码:

import pymysql

f = open(r"raspados_panda.csv", "r")
fString = f.read()

# convert string to list
fList = []
for line in fString.split('\n'):
    fList.append(line.split(','))

# open connection to database
db = pymysql.connect("localhost", "root", "asafajad", "raspados")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Drop table if it already exist using execute() method
cursor.execute("DROP TABLE IF EXISTS RASPADOS")

# create column names from the first line in fList
CATEGORIA = fList[0][0]; PARRAFO = fList[0][1]; FECHA = fList[0][2]; TITULO = fList[0][3]; IMAGEN = fList[0][4]

# create RASPADO table // place a comma after each new column except the last
queryCreateRaspadoTable = """CREATE TABLE RASPADOS(
                            {} VARCHAR(45),
                            {} TEXT,
                            {} VARCHAR(45),
                            {} VARCHAR(255),
                            {} VARCHAR(45)
                            )""".format(CATEGORIA, TITULO, FECHA, PARRAFO, IMAGEN)

cursor.execute(queryCreateRaspadoTable)

del fList[0]
rows = ''


for i in range(len(fList)-1):
    rows += "('{}','{}','{}','{}','{}')".format(fList[i][0], (fList[i][1]), (fList[i][2]), (fList[i][3]), (fList[i][4]))
    if i != len(fList) - 2:
        rows += ','

queryInsert = "INSERT INTO RASPADOS VALUES" + rows  # ('categoria', 'titulo', 'fecha', 'parrafo', 'imagen')

try:
    cursor.execute(queryInsert)
    db.commit()
except:
    db.rollback()


db.close()

我的难题是数据库没有显示任何数据。

pd:我需要将此代码包含在代码中,因为您无法自动执行mysql向导导入程序。

0 个答案:

没有答案