【问题标题】:Sqlite update row on unique valueSqlite 在唯一值上更新行
【发布时间】:2017-12-29 03:39:57
【问题描述】:

我正在从一个 csv 文件在 sqlite3 中创建一个表,该文件提供我必须使用的唯一 ID。我把它放在我创建数据库及其完整的地方。我正在尝试获取另一个具有相同唯一 id 值但添加了我想应用于数据库的信息的 csv 文件。

我想添加的 csv 文件仅适用于 db 中的许多行。我收到一个错误:IndexError: list index out of range

Traceback (most recent call last):
File "test.py", line 62, in <module>
update_teams(x[0], x[2])
IndexError: list index out of range

我得到这个是因为 csv 到 sqlite.db 的行数不同吗?

CSV 格式:

Id,PlayerName,TeamName
641393,John Doe1,Team1
663844,John Doe2,Team1
607469,John Doe3,Team1

我的代码:

import csv
import sqlite3

# connect to sqlite database
conn = sqlite3.connect('players.db')
c = conn.cursor()

# table values
table_spec = """CREATE TABLE IF NOT EXISTS players(
                player_id INTEGER UNIQUE,
                name_last TEXT,
                name_first TEXT,
                TeamName TEXT);"""


# Create Table
def create_table():
  c.execute(table_spec)


# Takes values and inserts them into the table
def write_core_data(player_id, name_last, name_first):
    c.execute('INSERT OR IGNORE 
               INTO players ("player_id","name_last","name_first") 
               VALUES (?,?,?)', (player_id,name_last, name_first))
    conn.commit()


def update_teams(player_id, TeamName):
    c.execute('UPDATE players 
               SET TeamName=? 
               WHERE player_id=?',(TeamName, player_id))
    conn.commit()


# create_table()


with open('players_master.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for x in readCSV:
        write_core_data(x[0], x[1], x[2])
        print(x[0])

with open('team_list.csv') as teamlist:
    readCSV = csv.reader(teamlist, delimiter=',')
    for x in readCSV:
        update_teams(x[0], x[2])
        print("Added team {} to {}".format(x[2], x[1]))

c.close()
conn.close()

非常感谢任何输入。谢谢你

【问题讨论】:

  • 这些 CSV 文件有多大? MB? GBs?
  • 感谢您的提问。 db 文件为 6,793KB,csv 文件为 334KB。所以它们真的很小,但我只是想,因为不同的行数可能是问题所在。
  • SQLite(和大多数数据库)不能这样工作。你不会用完行,当然不会用你拥有的少量数据。您能否突出显示问题发生在代码中的确切位置?
  • 为完整错误添加了块代码。该错误是由函数 update_teams() 创建的。如果 id 匹配,我相信我有正确的语法来提高条件,团队列中填充了值。

标签: python csv sqlite


【解决方案1】:

很可能,您的 cvs 文件有空行或行太短。 跳过空行:

for x in readCSV:
    if x:
        update_teams(x[0], x[2])

你也可以断言len(x) &gt;= 3:

for x in readCSV:
    if len(x) < 3:
        print('Skipping', x)
    else: 
        update_teams(x[0], x[2])

【讨论】:

  • 是的,这就是问题所在。感谢您的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2021-05-30
  • 2017-05-30
  • 2014-08-20
  • 2020-01-25
  • 1970-01-01
相关资源
最近更新 更多