从SQLite数据库获取时尝试/除外不起作用

时间:2019-04-29 23:48:46

标签: sql python-3.x sqlite

我正在建立一个应用程序,该程序可以从iTunes库导出中的XML文件提取不同的属性。由于并非每首歌都有一种流派,因此每首歌找到一首歌并不总是可行。当程序将流派插入“流派”时,它会创建一个自动ID

CREATE TABLE Genre (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name TEXT UNIQUE
);

问题是,当在XML文件中没有找到“流派”时,不会插入任何内容,这意味着我以后无法获取通过添加某些内容而创建的ID并将其放入Tabke以便进行关系查询。为了阻止这种情况,我将插入并提取到try /里面,除非会捕获

TypeError: 'NoneType' object is not subscriptable

无法执行时出现错误

cur.fetchone()[0]

。除此之外,我将流派设置为“无流派”,以在找不到流派的情况下生成唯一ID。即使它在try块中捕获了异常,也不会运行。错误:

TypeError                                 Traceback (most recent call last)
~\Documents\python\tracks.py in <module>
     83         cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
---> 84         genre_id = cur.fetchone()[0]
     85     except:

TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
~\Documents\python\tracks.py in <module>
     87         cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
     88         cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
---> 89         genre_id = cur.fetchone()[0]
     90 
     91 

TypeError: 'NoneType' object is not subscriptable 

帮助!为什么try / except不起作用?

    try:
        cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
        cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
        genre_id = cur.fetchone()[0]
    except:
        genre = "No Genre"
        cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
        cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
        genre_id = cur.fetchone()[0]

1 个答案:

答案 0 :(得分:0)

好的,首先解决方案

import sqlite3
conn = sqlite3.connect('systeminfo.db')
cur = conn.cursor()

genre = 'test'
try:
    cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
    cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
    genre_id = cur.fetchone()
    if genre_id is None:
        print('Select did not find any artist for {} genre'.format(genre))
    else:
        print('Select resulted in Artist ID {}'.format(genre_id[0]))
except Exception as e:
    print('Exception: {}'.format(e))
    raise Exception(e)

conn.commit()
conn.close()

请参阅,cur.fetchone()有可能导致一行,如果没有行,则可能会导致无。因此,让我们做一个if..then,然后检查None。

这似乎正在发生。滚动帖子底部的方式以找到答案。

表格

CREATE TABLE Artist (
    id integer not null primary key autoincrement,
    name text,
    genre text
);

CREATE TABLE Genre (
    id integer not null primary key autoincrement,
    name text unique
);

数据

sqlite> select * from Artist;
Run Time: real 0.000 user 0.000086 sys 0.000054
sqlite> select * from Genre;
Run Time: real 0.000 user 0.000092 sys 0.000064
sqlite>

基本上没有数据。

您的代码

import sqlite3
conn = sqlite3.connect('systeminfo.db')
cur = conn.cursor()

genre = 'test'
try:
    cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
    cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
    genre_id = cur.fetchone()[0]
except:
    cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
    cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
    genre_id = cur.fetchone()[0]

conn.commit()
conn.close()

问题

您的错误在2个地方发生。在您的try块中,genre_id = cur.fetchone()[0]处有错误。遇到错误后,控件将转到except块。在该块中,重复代码。就是说,重复错误。在该块中,没有错误处理,因为它是错误处理。因此,对于同一件事genre_id = cur.fetchone()[0],python在except块中引发了另一个错误。

解决问题

import sqlite3
conn = sqlite3.connect('systeminfo.db')
cur = conn.cursor()

genre = 'test'
try:
    cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', ( genre, ) )
    cur.execute('SELECT id FROM Artist WHERE name = ? ', (genre, ))
    genre_id = cur.fetchone()[0]
except Exception as e:
    print('Exception: {}'.format(e))

conn.commit()
conn.close()

好的。在except中,我们要处理异常并可能打印出异常。因此,我们将使用except Exception as e。现在,错误信息在e中。我们将其打印出来,就是这样。

$ python myfile.py
Exception: 'NoneType' object is not subscriptable

但是,如果我想显示错误在哪里呢?

raise Exception(e)下添加print('Exception: {}'.format(e))。因此,结果变为:

$ python myfile.py
Exception: 'NoneType' object is not subscriptable
Traceback (most recent call last):
  File "testy.py", line 9, in <module>
    genre_id = cur.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "testy.py", line 12, in <module>
    raise Exception(e)
Exception: 'NoneType' object is not subscriptable

raise语句在出现问题的屏幕上列出。