在sqlite3 Python中更改表的正确语法

时间:2017-06-13 15:22:45

标签: python sqlite

我试图从预定义的结构(structure_1)重新创建一个sqlite3数据库。我创建了一个db,然后通过structure_1数组重新创建每个表,以及我需要的每一列(使用正确的类型)。

我写了这个小python代码:

walkLength

使用structure_1看起来像这样:

sqlite_file = 'newdb.db'    # name of the sqlite database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

for table,field,field_type in structure_1:
    print table,field,field_type
    try: # if the table doesn't exist yet
        c.execute('CREATE TABLE {tn} ({nf} {ft});'.format(tn=table, nf=field, ft=field_type))
    except: # if the table exists already
        c.execute('ALTER TABLE {tn} ADD COLUMN {nf} {ft};'.format(tn=table, nf=field, ft=field_type))

不幸的是,代码返回错误:

[[u'countries', u'id', u'INTEGER'], [u'countries', u'iso', u'TEXT'], [u'countries', u'name', u'TEXT'], [u'countries', u'printable_name', u'TEXT'], [u'countries', u'iso3', u'TEXT'], [u'countries', u'numcode', u'NUMERIC'], [u'media_type', u'id', u'INTEGER'], [u'media_type', u'name', u'TEXT'], [u'space_types', u'id', u'INTEGER'], [u'space_types', u'name', u'TEXT'], [u'space_types', u'is_main_space', u'NUMERIC'], [u'users', u'guid', u'TEXT'], [u'users', u'id', u'INTEGER'], [u'users', u'nickname', u'TEXT'], [u'users', u'first_name', u'TEXT'], [u'users', u'last_name', u'TEXT'], [u'users', u'telephone', u'TEXT'], [u'users', u'address_1', u'TEXT'], [u'users', u'address_2', u'TEXT'], [u'users', u'region', u'TEXT'], [u'users', u'country', u'TEXT'], [u'users', u'language', u'TEXT'], [u'users', u'created_at', u'TEXT'], [u'users', u'updated_at', u'TEXT'], [u'attachment_spaces', u'guid', u'TEXT'], [u'attachment_spaces', u'ethics_url', u'TEXT'], [u'attachment_spaces', u'ethics_title', u'TEXT'], [u'attachment_spaces', u'file_url', u'TEXT'], [u'attachment_spaces', u'id', u'INTEGER'], [u'attachment_spaces', u'parent_id', u'TEXT'], [u'attachment_spaces', u'file_title', u'TEXT'], [u'human_spaces', u'guid', u'TEXT'], [u'human_spaces', u'id', u'INTEGER'], [u'human_spaces', u'parent_id', u'TEXT'], [u'human_spaces', u'first_name', u'TEXT'], [u'human_spaces', u'last_name', u'TEXT'], [u'human_spaces', u'date_of_birth', u'TEXT'], [u'human_spaces', u'address_1', u'TEXT'], [u'human_spaces', u'address_2', u'TEXT'], [u'human_spaces', u'telephone', u'TEXT'], [u'human_spaces', u'email', u'TEXT'], [u'human_spaces', u'first_name_birth', u'TEXT'], [u'human_spaces', u'last_name_birth', u'TEXT'], [u'human_spaces', u'other_surname', u'TEXT'], [u'human_spaces', u'gender', u'TEXT'], [u'human_spaces', u'city_of_birth', u'TEXT'], [u'human_spaces', u'country_of_birth', u'TEXT'], [u'human_spaces', u'date_of_death', u'TEXT'], [u'human_spaces', u'place_of_death', u'TEXT'], [u'interview_spaces', u'guid', u'TEXT'], [u'interview_spaces', u'id', u'INTEGER']]

这个错误可能来自哪里?我是否遗漏了sqlite3查询语法中的明显内容?

1 个答案:

答案 0 :(得分:-1)

传递给SQL查询的字符串可能存在问题。请尝试在它们周围使用单引号,方法是使用以下行:

c.execute("ALTER TABLE '{tn}' ADD COLUMN '{nf}' '{ft}';".format(tn=table, nf=field, ft=field_type))
相关问题