Complete guide to installing the Countries States Cities database in SQLite for lightweight, embedded applications
SQLite is a lightweight, file-based database that requires no separate server process. It’s perfect for mobile applications, prototypes, and embedded systems. This guide covers installing the Countries States Cities database in SQLite.
SQLite installation is the fastest option, typically taking less than 1 minute with approximately 50MB file size.
SQLite databases are self-contained files that don’t require a separate server installation, making them ideal for development and embedded applications.
This creates a new SQLite database file named world.db in your current directory.
2
Import SQL File
Copy
.read sqlite/world.sql
SQLite import is typically the fastest due to its lightweight nature and single-file architecture.
3
Verify Installation
Copy
-- List all tables.tables-- Check table schema.schema countries-- Count records in each tableSELECT 'countries' as table_name, COUNT(*) as count FROM countriesUNION ALLSELECT 'states', COUNT(*) FROM states UNION ALLSELECT 'cities', COUNT(*) FROM cities;
-- List all tables.tables-- Show table schemas.schema countries.schema states.schema cities-- Get table infoPRAGMA table_info(countries);PRAGMA table_info(states); PRAGMA table_info(cities);
-- Essential indexes for query performanceCREATE INDEX IF NOT EXISTS idx_countries_iso2 ON countries(iso2);CREATE INDEX IF NOT EXISTS idx_countries_iso3 ON countries(iso3);CREATE INDEX IF NOT EXISTS idx_countries_region ON countries(region);CREATE INDEX IF NOT EXISTS idx_states_country_id ON states(country_id);CREATE INDEX IF NOT EXISTS idx_states_name ON states(name);CREATE INDEX IF NOT EXISTS idx_states_country_name ON states(country_name);CREATE INDEX IF NOT EXISTS idx_cities_country_id ON cities(country_id);CREATE INDEX IF NOT EXISTS idx_cities_state_id ON cities(state_id);CREATE INDEX IF NOT EXISTS idx_cities_name ON cities(name);CREATE INDEX IF NOT EXISTS idx_cities_coordinates ON cities(latitude, longitude);CREATE INDEX IF NOT EXISTS idx_cities_country_name ON cities(country_name);
import sqlite3from contextlib import contextmanagerclass WorldDatabase: def __init__(self, db_path='world.db'): self.db_path = db_path @contextmanager def get_connection(self): conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row # Enable column access by name try: yield conn finally: conn.close() def get_countries(self, limit=None): with self.get_connection() as conn: cursor = conn.cursor() query = "SELECT * FROM countries" if limit: query += f" LIMIT {limit}" return cursor.execute(query).fetchall() def get_cities_by_country(self, country_name, limit=None): with self.get_connection() as conn: cursor = conn.cursor() query = """ SELECT name, latitude, longitude, state_name FROM cities WHERE country_name = ? """ if limit: query += f" LIMIT {limit}" return cursor.execute(query, (country_name,)).fetchall() def search_cities(self, search_term, limit=10): with self.get_connection() as conn: cursor = conn.cursor() query = """ SELECT name, country_name, state_name, latitude, longitude FROM cities WHERE name LIKE ? ORDER BY name LIMIT ? """ return cursor.execute(query, (f'%{search_term}%', limit)).fetchall()# Usage exampledb = WorldDatabase()# Get all countriescountries = db.get_countries(limit=10)for country in countries: print(f"{country['name']} ({country['iso2']})")# Get cities in a specific countryus_cities = db.get_cities_by_country('United States', limit=5)for city in us_cities: print(f"{city['name']}, {city['state_name']}")# Search for citieslondon_cities = db.search_cities('London')for city in london_cities: print(f"{city['name']}, {city['country_name']}")
Copy
const sqlite3 = require('sqlite3').verbose();class WorldDatabase { constructor(dbPath = 'world.db') { this.db = new sqlite3.Database(dbPath); } getCountries(limit = null) { return new Promise((resolve, reject) => { let query = "SELECT * FROM countries"; if (limit) query += ` LIMIT ${limit}`; this.db.all(query, (err, rows) => { if (err) reject(err); else resolve(rows); }); }); } getCitiesByCountry(countryName, limit = null) { return new Promise((resolve, reject) => { let query = ` SELECT name, latitude, longitude, state_name FROM cities WHERE country_name = ? `; if (limit) query += ` LIMIT ${limit}`; this.db.all(query, [countryName], (err, rows) => { if (err) reject(err); else resolve(rows); }); }); } searchCities(searchTerm, limit = 10) { return new Promise((resolve, reject) => { const query = ` SELECT name, country_name, state_name, latitude, longitude FROM cities WHERE name LIKE ? ORDER BY name LIMIT ? `; this.db.all(query, [`%${searchTerm}%`, limit], (err, rows) => { if (err) reject(err); else resolve(rows); }); }); } close() { this.db.close(); }}// Usage exampleasync function example() { const db = new WorldDatabase(); try { // Get countries const countries = await db.getCountries(5); console.log('Countries:', countries); // Get US cities const usCities = await db.getCitiesByCountry('United States', 5); console.log('US Cities:', usCities); // Search for cities const londonCities = await db.searchCities('London'); console.log('Cities named London:', londonCities); } catch (error) { console.error('Database error:', error); } finally { db.close(); }}example();
Copy
using Microsoft.Data.Sqlite;using System;using System.Collections.Generic;using System.Data;public class WorldDatabase : IDisposable{ private readonly SqliteConnection _connection; public WorldDatabase(string dbPath = "world.db") { string connectionString = $"Data Source={dbPath}"; _connection = new SqliteConnection(connectionString); _connection.Open(); } public List<Country> GetCountries(int? limit = null) { var countries = new List<Country>(); string query = "SELECT id, name, iso2, iso3, region FROM countries"; if (limit.HasValue) query += $" LIMIT {limit}"; using var command = new SqliteCommand(query, _connection); using var reader = command.ExecuteReader(); while (reader.Read()) { countries.Add(new Country { Id = reader.GetInt32("id"), Name = reader.GetString("name"), Iso2 = reader.GetString("iso2"), Iso3 = reader.GetString("iso3"), Region = reader.IsDBNull("region") ? null : reader.GetString("region") }); } return countries; } public List<City> GetCitiesByCountry(string countryName, int? limit = null) { var cities = new List<City>(); string query = @" SELECT name, latitude, longitude, state_name FROM cities WHERE country_name = @countryName"; if (limit.HasValue) query += $" LIMIT {limit}"; using var command = new SqliteCommand(query, _connection); command.Parameters.AddWithValue("@countryName", countryName); using var reader = command.ExecuteReader(); while (reader.Read()) { cities.Add(new City { Name = reader.GetString("name"), Latitude = reader.IsDBNull("latitude") ? null : reader.GetDouble("latitude"), Longitude = reader.IsDBNull("longitude") ? null : reader.GetDouble("longitude"), StateName = reader.IsDBNull("state_name") ? null : reader.GetString("state_name") }); } return cities; } public void Dispose() { _connection?.Dispose(); }}public class Country{ public int Id { get; set; } public string Name { get; set; } public string Iso2 { get; set; } public string Iso3 { get; set; } public string Region { get; set; }}public class City{ public string Name { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } public string StateName { get; set; }}// Usage exampleusing var db = new WorldDatabase();var countries = db.GetCountries(5);foreach (var country in countries){ Console.WriteLine($"{country.Name} ({country.Iso2})");}var usCities = db.GetCitiesByCountry("United States", 5);foreach (var city in usCities){ Console.WriteLine($"{city.Name}, {city.StateName}");}
# SQLite databases can be backed up by copying the filecp world.db world_backup_$(date +%Y%m%d).db# Compress backupgzip world_backup_$(date +%Y%m%d).db