sqlite3 обновление / добавление данных в новый столбец - PullRequest
0 голосов
/ 08 декабря 2018

Я создал новый столбец со значениями NULL , названными id в таблице.Теперь я хочу добавить данные к нему из списка.Он содержит около 130 тыс. Элементов.

Я попытался с помощью вставки, он вернул ошибку:

conn = create_connection(xml_db)
cursor = conn.cursor()
with conn:
    cursor.execute("ALTER TABLE xml_table ADD COLUMN id integer")
    for data in ssetId:
        cursor.execute("INSERT INTO xml_table(id) VALUES (?)", (data,))
        conn.commit()

Я также попытался с обновлением:

conn = create_connection(xml_db)
cursor = conn.cursor()
with conn:
    cursor.execute("ALTER TABLE xml_table ADD COLUMN id INTEGER")
    for data in ssetId:
        cursor.execute("UPDATE xml_table SET ('id' = ?)", (data,))
        conn.commit()

Что здесь неверного?

РЕДАКТИРОВАТЬ для уточнения.

Таблица уже существовала, заполненная данными.Я хочу добавить столбец "id" с пользовательскими значениями.

1 Ответ

0 голосов
/ 08 декабря 2018

Вот пример, похожий на ваш, который может быть полезен.

import sqlite3

conn = sqlite3.connect("xml.db")

cursor = conn.cursor()

with conn:

    # for testing purposes, remove this or else the table gets dropped whenever the file is loaded
    cursor.execute("drop table if exists xml_table")

    # create table with some other field
    cursor.execute("create table if not exists xml_table (other_field integer not null)")

    for other_data in range(5):
        cursor.execute("INSERT INTO xml_table (other_field) VALUES (?)", (other_data,))

    # add id field
    cursor.execute("ALTER TABLE xml_table ADD COLUMN id integer")

    # make sure the table exists
    res = cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    print("Table Name: {}".format(res.fetchone()[0]))

    # add data to the table
    for data in range(5):
        cursor.execute("UPDATE xml_table SET id = ? WHERE other_field = ?", (data, data))

    # if you must insert an id, you must specify a other_field value as well, since other_field must be not null
    cursor.execute("insert into xml_table (id, other_field) VALUES (? ,?)", (100, 105))


    # make sure data exists
    res = cursor.execute("SELECT id, other_field FROM xml_table")
    for id_result in res:
        print(id_result)

    conn.commit()

conn.close()

Как я уже говорил в комментарии ниже, поскольку одна из ваших строк имеет ограничение NOT NULL, никакие строки не могут существовать втаблица с этим столбцом NULL.В приведенном выше примере other_field указано NOT NULL, поэтому в столбце other_field не может быть строк, имеющих значения NULL.Любое отклонение от этого будет IntegrityError.

Выход:

Table Name: xml_table
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
(100, 105)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...