将特定信息从 CSV 插入到 SQL python3
Inserting specific information from CSV to SQL python3
我在将信息从 CSV 文件插入到 SQL 数据库时遇到了一些问题,
这是我正在使用的代码:
import csv
import pymysql
def sqlinsert(cur, vname, vid, file, db):
insertcsv = '''INSERT INTO `mydb`(VID,name,starttime,stoptime,sessiontime,calledstation,sessionbill)
VALUES(%s, %s, %s, %s, %s, %s, %s)'''
with open(os.path.join(cwd, 'RawCSV', file), 'r') as f:
reader = csv.reader(f, delimiter='\t')
next(reader) # skipping the first line
for row in reader:
cur.execute(insertcsv, (vid, vname, row[8:13]))
db.commit()
问题如下:
TypeError: not enough arguments for format string
如果我要从插入命令中删除 VID 和名称,然后这样做:
insertcsv = '''INSERT INTO `mydb (starttime,stoptime,sessiontime,calledstation,sessionbill) VALUES(%s, %s, %s, %s, %s)'''
cur.execute(insertcsv, row[8:13])
这将毫无问题地导入,我在这里缺少什么?
这是 CSV 行:
7869574006 1443580239 478 -00000027 1499347553.39 231 2017-07-06
1) 修正缩进
2) (vid, vname, row[8:13]) 将是 (t1, t2, []) 类型的元组。
其中 t1 和 t2 是 vid 和 vname 的类型。
尝试使用:
row_to_insert = [vid, vname] + row[8:13] # Appending the two lists.
cur.execute(insertcsv, row_to_insert)
我在将信息从 CSV 文件插入到 SQL 数据库时遇到了一些问题, 这是我正在使用的代码:
import csv
import pymysql
def sqlinsert(cur, vname, vid, file, db):
insertcsv = '''INSERT INTO `mydb`(VID,name,starttime,stoptime,sessiontime,calledstation,sessionbill)
VALUES(%s, %s, %s, %s, %s, %s, %s)'''
with open(os.path.join(cwd, 'RawCSV', file), 'r') as f:
reader = csv.reader(f, delimiter='\t')
next(reader) # skipping the first line
for row in reader:
cur.execute(insertcsv, (vid, vname, row[8:13]))
db.commit()
问题如下:
TypeError: not enough arguments for format string
如果我要从插入命令中删除 VID 和名称,然后这样做:
insertcsv = '''INSERT INTO `mydb (starttime,stoptime,sessiontime,calledstation,sessionbill) VALUES(%s, %s, %s, %s, %s)'''
cur.execute(insertcsv, row[8:13])
这将毫无问题地导入,我在这里缺少什么?
这是 CSV 行:
7869574006 1443580239 478 -00000027 1499347553.39 231 2017-07-06
1) 修正缩进
2) (vid, vname, row[8:13]) 将是 (t1, t2, []) 类型的元组。 其中 t1 和 t2 是 vid 和 vname 的类型。
尝试使用:
row_to_insert = [vid, vname] + row[8:13] # Appending the two lists.
cur.execute(insertcsv, row_to_insert)