如果不存在,如何在sqlite3 db dict中插入

时间:2019-07-17 12:56:15

标签: python-3.x sqlite

我有几个不同的字典,像这样:

result = {'url': url, 'league': league, 'home_team': home_team, 'away_team': away_team, 'current_time': current_time, 'current_score': current_score, 'autogoal_team': autogoal_team, 'autogoal_time': autogoal_time, 'autogoal_name': autogoal_name}
result = {'url': url, 'league': league, 'home_team': home_team, 'away_team': away_team, 'current_time': current_time, 'current_score': current_score, 'penalty_not_score_team': penalty_team, 'penalty_not_score_time': penalty_time, 'penalty_not_score_name': penalty_name}

如您所见,有很多项目,而我有更多类似的字典。 现在,我以这种方式插入数据:

cur.execute('SELECT * FROM MATCHES WHERE (url=? AND league=? AND home_team=?)', (url, league, home_team))
entry = cur.fetchone()

if entry is None:
    cur.execute('INSERT INTO MATCHES (url, league, home_team) VALUES (?,?,?)', (url, league, home_team))

所以这样做非常不舒服,因为我需要确保记录没有重复,而且我必须多次执行此代码。

告诉我,我可以做这样的事情吗?

cur.execute('SELECT * FROM MATCHES WHERE (?)', (my_dict))
entry = cur.fetchone()

if entry is None:
    cur.execute('INSERT INTO MATCHES (?)', (my_dict))

因此,我想检查数据库中是否已经存在这样的字典,如果不存在,请添加它。

1 个答案:

答案 0 :(得分:0)

如果您在这些值上建立唯一索引(即使在导入数据时只是临时索引,如果这样对进一步的查询无济于事),则可以使用INSERT OR IGNORE

类似的东西:

cur.execute("CREATE UNIQUE INDEX matches_idx_blah ON matches(url, league, home_team)")
for result in yourdata:
  cur.execute("INSERT OR IGNORE INTO matches(url, league, home_team) VALUES (?,?,?)", (result['url'], result['league'], result['home_team']))

这将导致任何尝试插入重复行的尝试都将失败,而不会真正产生错误。