Sửa lỗi “Integrity constraint violation” sau khi thêm bớt column trong table của SQLite database

Trong quá trình phát triển tôi hay thường phải “ALTER” để thêm bớt column trong table của SQLite database và thi thoảng điều đó gây tai họa đó là gặp phải lỗi “Integrity constraint violation” mỗi khi cố gắng INSERT thêm một hàng vào table.

SQLSTATE[23000]: Integrity constraint violation: 19 constraint failed

Tôi cũng chẳng hiểu nguyên nhân gì gây ra chuyện này vì mình cũng thực hiện đúng theo syntax đã hướng dẫn.

Giải pháp sửa của tôi đó là đành phải copy dữ liệu ra một table khác giống Y HỆT về cấu trúc, DROP cái cũ đi rồi RENAME table mới về table cũ và lỗi đó biến mất (?!)

# Create a new table which has EXACTLY the same column definitions
CREATE TABLE `temp_tbl` (id INTEGER PRIMARY KEY,col1 as TEXT, col2 as INTEGER);

# Copy all data from the old table to the new one
INSERT INTO `temp_tbl` SELECT * FROM `bad_table`;

# Drop the old table and rename the newly created table name to the old one's
DROP TABLE bad_table;
ALTER TABLE temp_tbl RENAME TO bad_table;

Phản hồi về bài viết

Cùng thảo luận chút nhỉ!

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.