Modify a Column's Type in sqlite3

前端 未结 4 1701
日久生厌
日久生厌 2020-11-29 01:13

I\'m pretty new to SQLite 3 and just now I had to add a column to an existing table I had. I went about doing that by doing: ALTER TABLE thetable ADD COLUMN category;<

相关标签:
4条回答
  • 2020-11-29 01:55

    It is possible by recreating table.Its work for me please follow following step:

    1. create temporary table using as select * from your table
    2. drop your table, create your table using modify column type
    3. now insert records from temp table to your newly created table
    4. drop temporary table

    do all above steps in worker thread to reduce load on uithread

    0 讨论(0)
  • 2020-11-29 02:04

    SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.

    See also:

    • SQLite Modify Column
    0 讨论(0)
  • 2020-11-29 02:05

    If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

    1. "File" - "Open Database"
    2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

    DB Browser for SQLite is open source and free. For Linux it is available from the repository.

    0 讨论(0)
  • 2020-11-29 02:15

    It is possible by dumping, editing and reimporting the table.

    This script will do it for you (Adapt the values at the start of the script to your needs):

    #!/bin/bash
    
    DB=/tmp/synapse/homeserver.db
    TABLE="public_room_list_stream"
    FIELD=visibility
    OLD="BOOLEAN NOT NULL"
    NEW="INTEGER NOT NULL"
    TMP=/tmp/sqlite_$TABLE.sql
    
    echo "### create dump"
    echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP
    
    echo "### editing the create statement"
    sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP
    
    read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 
    
    echo "### rename the original to '$TABLE"_backup"'"
    sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"
    
    echo "### delete the old indexes"
    for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
      echo "DROP INDEX '$idx';" | sqlite3 $DB
    done
    
    echo "### reinserting the edited table"
    cat $TMP | sqlite3 $DB
    
    0 讨论(0)
提交回复
热议问题