When I import a csv file to sqlite database, it imports number as string to integer column, how can I fix this? A line from my csv file like this:
31,c,BB ROSE - 031,c31,,9,7,0,"142,000",0
When I import a csv file to sqlite database, it imports number as string to integer column, how can I fix this? A line from my csv file like this:
31,c,BB ROSE - 031,c31,,9,7,0,"142,000",0
When importing csv files, SQLite assumes all fields are text fields. So you need to perform some extra steps in order to set the correct data types.
However, it is my understanding that you cannot use the
ALTER TABLE
statement to modify a column in SQLite. Instead, you will need to rename the table, create a new table, and copy the data into the new table.https://www.techonthenet.com/sqlite/tables/alter_table.php
So suppose I have an employees.csv file I want to import into SQLite database with the correct data types.
First, create a SQLite database called
mydb.sqlite
and importemployees.csv
into a SQLite table calledemployees
.At this point, the data is imported as text. Let's first get the
employees
schema from the database and save it toemployees.sql
.We can use this to create a new script that would rename the table, create a new table, and copy the data into the new table.You should now have employees.sql with the following schema:
Let's now create a SQL filed called alterTable.sql that would rename the table, create a new table, and copy the data into the new table.
alterTable.sql
Finally, we can execute SQL in
alterTable.sql
and drop the old renamed tableAt this point, the imported employee data should have the correct data types instead of the default text field.
If you do it this way, you don't have to worry about headers in csv file being imported as data. Other methods might require you delete the header either before or after importing the csv file.
CSV files do no have data types; everything is a string.
To convert all values in a column into a number, use something like this:
In SQLite, you cannot change the type affinities of columns. Therefore you should
create
your table and then.import
your CSV file into the table. If your CSV file has a header, that will be treated as data upon import. You can either delete the header before importing (in the CSV file), or delete the header after import (in the table). Since thetypeof
all the header fields will beTEXT
, you can easily find this header in a table where some columns have numeric type affinities.