Tutorials
sql
+2

SQLite in Python

In this tutorial, you will learn about using SQLite, an extremely light-weight Relational database management system (RDBMS) in Python.

Relational database management systems (RDBMS) are extremely popular and are quite an integral part of application development. Many different RDBMS exist, for example, MySQL, PostgreSQL, IBM DB2, Oracle 11g and so on. Such an RDBMS is SQLite. SQLite is widely-used and is favorite among the developers for many reasons -

  • Extremely light-weighted (not more than 500 KBs)
  • It is serverless which means you do not need any separate server for availing its services
  • No complex setup
  • Fully transactional and concurrency-compliant
  • and many more...

However, there are some limitations of SQLite as well. For example, it does not support joins like RIGHT OUTER JOIN and FULL OUTER JOIN. But the advantages are way more than the limitations. In this tutorial, you will be introduced to using SQLite in Python and following is the overview of the contents this tutorial covers -

  • Installation and setup of SQLite
  • Creating databases and tables in SQLite
  • Importing a .csv file into a SQLite database
  • SQLite in Python

Note: This tutorial assumes that you are already familiar with the basics of SQL (using any RDBMS) and Python (3). If you want to refresh these skills, the following resources might come in handy -

Once you feel comfortable working with SQL and Python, you can come back and resume from where you left off.

Installation and setup

Installing and setting up SQLite takes a matter of a few minutes. You can use SQLite from the command line tools, but there is a GUI-based utility which lets you use SQLite through a decent graphical interface. For this tutorial, you will be using DB Browser for SQLite. To start, you will first download this tool from here with respect to your OS platform.

On a Windows 7 platform, the interface for DB Browser for SQLite looks like this -

Creating databases and tables

Once you are ready with the DB Browser tool, you can create a new SQLite database to proceed. To do this, you can click on the New Database tab -

After clicking on the New Database tab, you will be prompted to enter a name for the database. Give a name of your choice and then proceed. An empty database of the name that you entered will be created instantaneously, and you will be prompted to create a table under that database. You can skip the table creation part, for now, you will get to it shortly.

To create a table, you need to fix upon the schema of the table. For this tutorial and the sake of understanding let's first create a simple table named consumers with the following field and data-types -

  • consumer_id (integer)
  • consumer_full_name (string) (cannot be null)
  • consumer_email (string) (cannot be null)
  • consumer_grade (character) (cannot be null)

Note: If you are familiar with database schema designing, you might recollect that the field consumer_id is the primary key of the table (that is why it is underlined).

To create a table, click on the Create Table tab and you will be prompted to enter the details of the table that you wish to create -

If you look closely at the above figure, you will see that it contains the exact details that you wanted to be incorporated in the table consumers. You can also see the respective SQL to create the table. The DB Browser tool lets you do this very efficiently. Once you followed this, click on the OK button and the table consumers should appear under the database that you created sometime back -

The table sqlite_sequence is there because if you specified the consumer_id field to be auto-incremented, SQLite creates a separate table to maintain the sequences. You can execute other SQL queries also by going to the Execute SQL section. Feel free to execute some of your favorite SQL queries.

Now before interacting with SQLite databases using Python, let's see how you can import a .csv file into a SQLite database and use it for analysis.

Importing a .csv file into a SQLite database

To import a .csv file into the database you created, just follow this navigation: File -> Import -> Table from CSV file. You can use this .csv file for the purpose. It contains details about different countries around the globe. Navigate to the file, and you will get a dialog box like the following after that -

DB Browser lets you specify many things here including the names of the table. Make sure you check the Column names in the first line option so that SQLite can extract the column names automatically. Click on OK after you are done with the specifications.

You should be able to see an entry for the table -

Feel free to execute some select queries to see if the table was imported correctly or not.

SQLite in Python

You now have a database and a table ready to work with. To be able to interact with a SQLite database using Python, you would need the sqlite3 module which comes with the Anaconda distribution.

Now, you will connect to the database that you created using the connect() method provided by sqlite3. This returns a Connection object. Supply the path of the database to the connect method. Databases are generally saved in .db extension.

import sqlite3

conn = sqlite3.connect('tutorial.db')

Once you have a Connection to the database, you can create a Cursor object and call its execute() method to perform SQL commands.

cur = conn.cursor()
cur.execute('SELECT * from countries')
<sqlite3.Cursor at 0x398ace0>

After executing the SELECT statement, you can -

  • treat the cursor object cur as an iterator call the fetchone() method to display a single row or
  • call the fetchall() method to display a list of rows

Let's try both one by one.

print(cur.fetchone())
('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', '1919', 'Afganistan/Afqanestan', 'Islamic Emirate', 'Kabul')
print(cur.fetchall())
[('NLD', 'Netherlands', 'Europe', 'Western Europe', '1581', 'Nederland', 'Constitutional Monarchy', 'Amsterdam'), ('ALB', 'Albania', 'Europe', 'Southern Europe', '1912', 'Shqiperia', 'Republic', 'Tirane'), ('DZA', 'Algeria', 'Africa', 'Northern Africa', '1962', 'Al-Jaza\x92ir/Algerie', 'Republic', 'Algiers'), ('ASM', 'American Samoa', 'Oceania', 'Polynesia', None, 'Amerika Samoa', 'US Territory', 'Pago Pago'), ('AND', 'Andorra', 'Europe', 'Southern Europe', '1278', 'Andorra', 'Parliamentary Coprincipality', 'Andorra la Vella'), ('AGO', 'Angola', 'Africa', 'Central Africa', '1975', 'Angola', 'Republic', 'Luanda'), ('ATG', 'Antigua and Barbuda', 'North America', 'Caribbean', '1981', 'Antigua and Barbuda', 'Constitutional Monarchy', "Saint John's"), ('ARE', 'United Arab Emirates', 'Asia', 'Middle East', '1971', 'Al-Imarat al-´Arabiya al-Muttahida', 'Emirate Federation', 'Abu Dhabi'), ('ARG', 'Argentina', 'South America', 'South America', '1816', 'Argentina', 'Federal Republic', 'Buenos Aires'), ('ARM', 'Armenia', 'Asia', 'Middle East', '1991', 'Hajastan', 'Republic', 'Yerevan'), ('ABW', 'Aruba', 'North America', 'Caribbean', None, 'Aruba', 'Nonmetropolitan Territory of The Netherlands', 'Oranjestad'), ('AUS', 'Australia', 'Oceania', 'Australia and New Zealand', '1901', 'Australia', 'Constitutional Monarchy, Federation', 'Canberra'), ('AZE', 'Azerbaijan', 'Asia', 'Middle East', '1991', 'Azarbaycan', 'Federal Republic', 'Baku'), ('BHS', 'Bahamas', 'North America', 'Caribbean', '1973', 'The Bahamas', 'Constitutional Monarchy', 'Nassau'), ('BHR', 'Bahrain', 'Asia', 'Middle East', '1971', 'Al-Bahrayn', 'Monarchy (Emirate)', 'Manama'), ('BGD', 'Bangladesh', 'Asia', 'Southern and Central Asia', '1971', 'Bangladesh', 'Republic', 'Dhaka'), ('BRB', 'Barbados', 'North America', 'Caribbean', '1966', 'Barbados', 'Constitutional Monarchy', 'Bridgetown'), ('BEL', 'Belgium', 'Europe', 'Western Europe', '1830', 'Belgie/Belgique', 'Constitutional Monarchy, Federation', 'Brussels'), ('BLZ', 'Belize', 'North America', 'Central America', '1981', 'Belize', 'Constitutional Monarchy', 'Belmopan'), ('BEN', 'Benin', 'Africa', 'Western Africa', '1960', 'Benin', 'Republic', 'Porto-Novo'), ('BMU', 'Bermuda', 'North America', 'North America', None, 'Bermuda', 'Dependent Territory of the UK', 'Hamilton'), ('BTN', 'Bhutan', 'Asia', 'Southern and Central Asia', '1910', 'Druk-Yul', 'Monarchy', 'Thimphu'), ('BOL', 'Bolivia', 'South America', 'South America', '1825', 'Bolivia', 'Republic', 'La Paz'), ('BIH', 'Bosnia and Herzegovina', 'Europe', 'Southern Europe', '1992', 'Bosna i Hercegovina', 'Federal Republic', 'Sarajevo'), ('BWA', 'Botswana', 'Africa', 'Southern Africa', '1966', 'Botswana', 'Republic', 'Gaborone'), ('BRA', 'Brazil', 'South America', 'South America', '1822', 'Brasil', 'Federal Republic', 'Brasilia'), ('GBR', 'United Kingdom', 'Europe', 'British Islands', '1066', 'United Kingdom', 'Constitutional Monarchy', 'London'), ('VGB', 'Virgin Islands, British', 'North America', 'Caribbean', None, 'British Virgin Islands', 'Dependent Territory of the UK', 'Road Town'), ('BRN', 'Brunei', 'Asia', 'Southeast Asia', '1984', 'Brunei Darussalam', 'Monarchy (Sultanate)', 'Bandar Seri Begawan'), ('BGR', 'Bulgaria', 'Europe', 'Eastern Europe', '1908', 'Balgarija', 'Republic', 'Sofia'), ('BFA', 'Burkina Faso', 'Africa', 'Western Africa', '1960', 'Burkina Faso', 'Republic', 'Ouagadougou'), ('BDI', 'Burundi', 'Africa', 'Eastern Africa', '1962', 'Burundi/Uburundi', 'Republic', 'Bujumbura'), ('CYM', 'Cayman Islands', 'North America', 'Caribbean', None, 'Cayman Islands', 'Dependent Territory of the UK', 'George Town'), ('CHL', 'Chile', 'South America', 'South America', '1810', 'Chile', 'Republic', 'Santiago'), ('CRI', 'Costa Rica', 'North America', 'Central America', '1821', 'Costa Rica', 'Republic', 'San Jose'), ('DJI', 'Djibouti', 'Africa', 'Eastern Africa', '1977', 'Djibouti/Jibuti', 'Republic', 'Djibouti'), ('DMA', 'Dominica', 'North America', 'Caribbean', '1978', 'Dominica', 'Republic', 'Roseau'), ('DOM', 'Dominican Republic', 'North America', 'Caribbean', '1844', 'Republica Dominicana', 'Republic', 'Santo Domingo'), ('ECU', 'Ecuador', 'South America', 'South America', '1822', 'Ecuador', 'Republic', 'Quito'), ('EGY', 'Egypt', 'Africa', 'Northern Africa', '1922', 'Misr', 'Republic', 'Cairo'), ('SLV', 'El Salvador', 'North America', 'Central America', '1841', 'El Salvador', 'Republic', 'San Salvador'), ('ERI', 'Eritrea', 'Africa', 'Eastern Africa', '1993', 'Ertra', 'Republic', 'Asmara'), ('ESP', 'Spain', 'Europe', 'Southern Europe', '1492', 'Espana', 'Constitutional Monarchy', 'Madrid'), ('ZAF', 'South Africa', 'Africa', 'Southern Africa', '1910', 'South Africa', 'Republic', 'Pretoria'), ('ETH', 'Ethiopia', 'Africa', 'Eastern Africa', '-1000', 'YeItyop´iya', 'Republic', 'Addis Ababa'), ('FJI', 'Fiji Islands', 'Oceania', 'Melanesia', '1970', 'Fiji Islands', 'Republic', 'Suva'), ('PHL', 'Philippines', 'Asia', 'Southeast Asia', '1946', 'Pilipinas', 'Republic', 'Manila'), ('FRO', 'Faroe Islands', 'Europe', 'Nordic Countries', None, 'Foroyar', 'Part of Denmark', 'Torshavn'), ('GAB', 'Gabon', 'Africa', 'Central Africa', '1960', 'Le Gabon', 'Republic', 'Libreville'), ('GMB', 'Gambia', 'Africa', 'Western Africa', '1965', 'The Gambia', 'Republic', 'Banjul'), ('GEO', 'Georgia', 'Asia', 'Middle East', '1991', 'Sakartvelo', 'Republic', 'Tbilisi'), ('GHA', 'Ghana', 'Africa', 'Western Africa', '1957', 'Ghana', 'Republic', 'Accra'), ('GIB', 'Gibraltar', 'Europe', 'Southern Europe', None, 'Gibraltar', 'Dependent Territory of the UK', None), ('GRD', 'Grenada', 'North America', 'Caribbean', '1974', 'Grenada', 'Constitutional Monarchy', "Saint George's"), ('GRL', 'Greenland', 'North America', 'North America', None, 'Kalaallit Nunaat/Gronland', 'Part of Denmark', 'Nuuk'), ('GUM', 'Guam', 'Oceania', 'Micronesia', None, 'Guam', 'US Territory', 'Agana'), ('GTM', 'Guatemala', 'North America', 'Central America', '1821', 'Guatemala', 'Republic', 'Guatemala City'), ('GIN', 'Guinea', 'Africa', 'Western Africa', '1958', 'Guinee', 'Republic', 'Conakry'), ('GNB', 'Guinea-Bissau', 'Africa', 'Western Africa', '1974', 'Guine-Bissau', 'Republic', 'Bissau'), ('GUY', 'Guyana', 'South America', 'South America', '1966', 'Guyana', 'Republic', 'Georgetown'), ('HTI', 'Haiti', 'North America', 'Caribbean', '1804', 'Haiti/Dayti', 'Republic', 'Port-au-Prince'), ('HND', 'Honduras', 'North America', 'Central America', '1838', 'Honduras', 'Republic', 'Tegucigalpa'), ('HKG', 'Hong Kong', 'Asia', 'Eastern Asia', None, 'Xianggang/Hong Kong', 'Special Administrative Region of China', None), ('IDN', 'Indonesia', 'Asia', 'Southeast Asia', '1945', 'Indonesia', 'Republic', 'Jakarta'), ('IND', 'India', 'Asia', 'Southern and Central Asia', '1947', 'Bharat/India', 'Federal Republic', 'New Delhi'), ('IRQ', 'Iraq', 'Asia', 'Middle East', '1932', 'Al-´Iraq', 'Republic', 'Baghdad'), ('IRN', 'Iran', 'Asia', 'Southern and Central Asia', '1906', 'Iran', 'Islamic Republic', 'Tehran'), ('IRL', 'Ireland', 'Europe', 'British Islands', '1921', 'Ireland/Eire', 'Republic', 'Dublin'), ('ISL', 'Iceland', 'Europe', 'Nordic Countries', '1944', 'Island', 'Republic', 'Reykjavik'), ('ISR', 'Israel', 'Asia', 'Middle East', '1948', 'Yisra\x92el/Isra\x92il', 'Republic', None), ('ITA', 'Italy', 'Europe', 'Southern Europe', '1861', 'Italia', 'Republic', 'Rome'), ('AUT', 'Austria', 'Europe', 'Western Europe', '1918', 'Osterreich', 'Federal Republic', 'Vienna'), ('JAM', 'Jamaica', 'North America', 'Caribbean', '1962', 'Jamaica', 'Constitutional Monarchy', 'Kingston'), ('JPN', 'Japan', 'Asia', 'Eastern Asia', '-660', 'Nihon/Nippon', 'Constitutional Monarchy', 'Tokyo'), ('YEM', 'Yemen', 'Asia', 'Middle East', '1918', 'Al-Yaman', 'Republic', "Sana'a"), ('JOR', 'Jordan', 'Asia', 'Middle East', '1946', 'Al-Urdunn', 'Constitutional Monarchy', 'Amman'), ('KHM', 'Cambodia', 'Asia', 'Southeast Asia', '1953', 'Kampuchea', 'Constitutional Monarchy', 'Phnom Penh'), ('CMR', 'Cameroon', 'Africa', 'Central Africa', '1960', 'Cameroun/Cameroon', 'Republic', 'Yaounde'), ('CAN', 'Canada', 'North America', 'North America', '1867', 'Canada', 'Constitutional Monarchy, Federation', 'Ottawa'), ('CPV', 'Cape Verde', 'Africa', 'Western Africa', '1975', 'Cabo Verde', 'Republic', 'Praia'), ('KAZ', 'Kazakhstan', 'Asia', 'Southern and Central Asia', '1991', 'Qazaqstan', 'Republic', 'Astana'), ('KEN', 'Kenya', 'Africa', 'Eastern Africa', '1963', 'Kenya', 'Republic', 'Nairobi'), ('CAF', 'Central African Republic', 'Africa', 'Central Africa', '1960', 'Centrafrique/Be-Afrika', 'Republic', 'Bangui'), ('CHN', 'China', 'Asia', 'Eastern Asia', '-1523', 'Zhongquo', "People'sRepublic", 'Beijing'), ('KGZ', 'Kyrgyzstan', 'Asia', 'Southern and Central Asia', '1991', 'Kyrgyzstan', 'Republic', 'Bishkek'), ('KIR', 'Kiribati', 'Oceania', 'Micronesia', '1979', 'Kiribati', 'Republic', 'Tarawa'), ('COL', 'Colombia', 'South America', 'South America', '1810', 'Colombia', 'Republic', 'Bogota'), ('COM', 'Comoros', 'Africa', 'Eastern Africa', '1975', 'Komori/Comores', 'Republic', 'Moroni'), ('COG', 'Congo', 'Africa', 'Central Africa', '1960', 'Congo', 'Republic', 'Brazzaville'), ('COD', 'Congo, The Democratic Republic of the', 'Africa', 'Central Africa', '1960', 'Republique Democratique du Congo', 'Republic', 'Kinshasa'), ('PRK', 'North Korea', 'Asia', 'Eastern Asia', '1948', 'Choson Minjujuui In´min Konghwaguk (Bukhan)', 'Socialistic Republic', 'Pyongyang'), ('KOR', 'South Korea', 'Asia', 'Eastern Asia', '1948', 'Taehan Min\x92guk (Namhan)', 'Republic', 'Seoul'), ('GRC', 'Greece', 'Europe', 'Southern Europe', '1830', 'Ellada', 'Republic', 'Athens'), ('HRV', 'Croatia', 'Europe', 'Southern Europe', '1991', 'Hrvatska', 'Republic', 'Zagreb'), ('CUB', 'Cuba', 'North America', 'Caribbean', '1902', 'Cuba', 'Socialistic Republic', 'Havana'), ('KWT', 'Kuwait', 'Asia', 'Middle East', '1961', 'Al-Kuwayt', 'Constitutional Monarchy (Emirate)', 'Kuwait City'), ('CYP', 'Cyprus', 'Asia', 'Middle East', '1960', 'Kypros/Kibris', 'Republic', 'Nicosia'), ('LAO', 'Laos', 'Asia', 'Southeast Asia', '1953', 'Lao', 'Republic', 'Vientiane'), ('LVA', 'Latvia', 'Europe', 'Baltic Countries', '1991', 'Latvija', 'Republic', 'Riga'), ('LSO', 'Lesotho', 'Africa', 'Southern Africa', '1966', 'Lesotho', 'Constitutional Monarchy', 'Maseru'), ('LBN', 'Lebanon', 'Asia', 'Middle East', '1941', 'Lubnan', 'Republic', 'Beirut'), ('LBR', 'Liberia', 'Africa', 'Western Africa', '1847', 'Liberia', 'Republic', 'Monrovia'), ('LBY', 'Libya', 'Africa', 'Northern Africa', '1951', 'Libiya', 'Socialistic State', 'Tripoli'), ('LIE', 'Liechtenstein', 'Europe', 'Western Europe', '1806', 'Liechtenstein', 'Constitutional Monarchy', 'Vaduz'), ('LTU', 'Lithuania', 'Europe', 'Baltic Countries', '1991', 'Lietuva', 'Republic', 'Vilnius'), ('LUX', 'Luxembourg', 'Europe', 'Western Europe', '1867', 'Luxembourg/Letzebuerg', 'Constitutional Monarchy', 'Luxembourg'), ('MAC', 'Macao', 'Asia', 'Eastern Asia', None, 'Macau/Aomen', 'Special Administrative Region of China', None), ('MDG', 'Madagascar', 'Africa', 'Eastern Africa', '1960', 'Madagasikara/Madagascar', 'Federal Republic', 'Antananarivo'), ('MKD', 'Macedonia', 'Europe', 'Southern Europe', '1991', 'Makedonija', 'Republic', 'Skopje'), ('MWI', 'Malawi', 'Africa', 'Eastern Africa', '1964', 'Malawi', 'Republic', 'Lilongwe'), ('MDV', 'Maldives', 'Asia', 'Southern and Central Asia', '1965', 'Dhivehi Raajje/Maldives', 'Republic', 'Male'), ('MYS', 'Malaysia', 'Asia', 'Southeast Asia', '1957', 'Malaysia', 'Constitutional Monarchy, Federation', 'Kuala Lumpur'), ('MLI', 'Mali', 'Africa', 'Western Africa', '1960', 'Mali', 'Republic', 'Bamako'), ('MLT', 'Malta', 'Europe', 'Southern Europe', '1964', 'Malta', 'Republic', 'Valletta'), ('MAR', 'Morocco', 'Africa', 'Northern Africa', '1956', 'Al-Maghrib', 'Constitutional Monarchy', 'Rabat'), ('MHL', 'Marshall Islands', 'Oceania', 'Micronesia', '1990', 'Marshall Islands/Majol', 'Republic', 'Majuro'), ('MRT', 'Mauritania', 'Africa', 'Western Africa', '1960', 'Muritaniya/Mauritanie', 'Republic', 'Nouakchott'), ('MUS', 'Mauritius', 'Africa', 'Eastern Africa', '1968', 'Mauritius', 'Republic', 'Port Louis'), ('MEX', 'Mexico', 'North America', 'Central America', '1810', 'Mexico', 'Federal Republic', 'Mexico City'), ('FSM', 'Micronesia, Federated States of', 'Oceania', 'Micronesia', '1990', 'Micronesia', 'Federal Republic', 'Palikir'), ('MDA', 'Moldova', 'Europe', 'Eastern Europe', '1991', 'Moldova', 'Republic', 'Chisinau'), ('MCO', 'Monaco', 'Europe', 'Western Europe', '1861', 'Monaco', 'Constitutional Monarchy', 'Monaco'), ('MNG', 'Mongolia', 'Asia', 'Eastern Asia', '1921', 'Mongol Uls', 'Republic', 'Ulaanbaatar'), ('MOZ', 'Mozambique', 'Africa', 'Eastern Africa', '1975', 'Mocambique', 'Republic', 'Maputo'), ('MMR', 'Myanmar', 'Asia', 'Southeast Asia', '1948', 'Myanma Pye', 'Republic', 'Naypyidaw'), ('NAM', 'Namibia', 'Africa', 'Southern Africa', '1990', 'Namibia', 'Republic', 'Windhoek'), ('NRU', 'Nauru', 'Oceania', 'Micronesia', '1968', 'Naoero/Nauru', 'Republic', 'Yaren District'), ('NPL', 'Nepal', 'Asia', 'Southern and Central Asia', '1769', 'Nepal', 'Constitutional Monarchy', 'Kathmandu'), ('NIC', 'Nicaragua', 'North America', 'Central America', '1838', 'Nicaragua', 'Republic', 'Managua'), ('NER', 'Niger', 'Africa', 'Western Africa', '1960', 'Niger', 'Republic', 'Niamey'), ('NGA', 'Nigeria', 'Africa', 'Western Africa', '1960', 'Nigeria', 'Federal Republic', 'Abuja'), ('NOR', 'Norway', 'Europe', 'Nordic Countries', '1905', 'Norge', 'Constitutional Monarchy', 'Oslo'), ('CIV', "Cote d'Ivoire", 'Africa', 'Western Africa', '1960', 'Cote d\x92Ivoire', 'Republic', 'Yamoussoukro'), ('OMN', 'Oman', 'Asia', 'Middle East', '1951', '´Uman', 'Monarchy (Sultanate)', 'Muscat'), ('PAK', 'Pakistan', 'Asia', 'Southern and Central Asia', '1947', 'Pakistan', 'Republic', 'Islamabad'), ('PLW', 'Palau', 'Oceania', 'Micronesia', '1994', 'Belau/Palau', 'Republic', 'Koror'), ('PAN', 'Panama', 'North America', 'Central America', '1903', 'Panama', 'Republic', 'Panama City'), ('PNG', 'Papua New Guinea', 'Oceania', 'Melanesia', '1975', 'Papua New Guinea/Papua Niugini', 'Constitutional Monarchy', 'Port Moresby'), ('PRY', 'Paraguay', 'South America', 'South America', '1811', 'Paraguay', 'Republic', 'Asuncion'), ('PER', 'Peru', 'South America', 'South America', '1821', 'Peru/Piruw', 'Republic', 'Lima'), ('MNP', 'Northern Mariana Islands', 'Oceania', 'Micronesia', None, 'Northern Mariana Islands', 'Commonwealth of the US', 'Saipan'), ('PRT', 'Portugal', 'Europe', 'Southern Europe', '1143', 'Portugal', 'Republic', 'Lisbon'), ('PRI', 'Puerto Rico', 'North America', 'Caribbean', None, 'Puerto Rico', 'Commonwealth of the US', 'San Juan'), ('POL', 'Poland', 'Europe', 'Eastern Europe', '1918', 'Polska', 'Republic', 'Warsaw'), ('GNQ', 'Equatorial Guinea', 'Africa', 'Central Africa', '1968', 'Guinea Ecuatorial', 'Republic', 'Malabo'), ('QAT', 'Qatar', 'Asia', 'Middle East', '1971', 'Qatar', 'Monarchy', 'Doha'), ('FRA', 'France', 'Europe', 'Western Europe', '843', 'France', 'Republic', 'Paris'), ('PYF', 'French Polynesia', 'Oceania', 'Polynesia', None, 'Polynesie francaise', 'Nonmetropolitan Territory of France', 'Papeete'), ('RWA', 'Rwanda', 'Africa', 'Eastern Africa', '1962', 'Rwanda/Urwanda', 'Republic', 'Kigali'), ('SWE', 'Sweden', 'Europe', 'Nordic Countries', '836', 'Sverige', 'Constitutional Monarchy', 'Stockholm'), ('KNA', 'Saint Kitts and Nevis', 'North America', 'Caribbean', '1983', 'Saint Kitts and Nevis', 'Constitutional Monarchy', 'Basseterre'), ('LCA', 'Saint Lucia', 'North America', 'Caribbean', '1979', 'Saint Lucia', 'Constitutional Monarchy', 'Castries'), ('VCT', 'Saint Vincent and the Grenadines', 'North America', 'Caribbean', '1979', 'Saint Vincent and the Grenadines', 'Constitutional Monarchy', 'Kingstown'), ('DEU', 'Germany', 'Europe', 'Western Europe', '1955', 'Deutschland', 'Federal Republic', 'Berlin'), ('SLB', 'Solomon Islands', 'Oceania', 'Melanesia', '1978', 'Solomon Islands', 'Constitutional Monarchy', 'Honiara'), ('ZMB', 'Zambia', 'Africa', 'Eastern Africa', '1964', 'Zambia', 'Republic', 'Lusaka'), ('WSM', 'Samoa', 'Oceania', 'Polynesia', '1962', 'Samoa', 'Parlementary Monarchy', 'Apia'), ('SMR', 'San Marino', 'Europe', 'Southern Europe', '885', 'San Marino', 'Republic', 'San Marino'), ('STP', 'Sao Tome and Principe', 'Africa', 'Central Africa', '1975', 'Sao Tome e Principe', 'Republic', 'Sao Tome'), ('SAU', 'Saudi Arabia', 'Asia', 'Middle East', '1932', 'Al-´Arabiya as-Sa´udiya', 'Monarchy', 'Riyadh'), ('SEN', 'Senegal', 'Africa', 'Western Africa', '1960', 'Senegal/Sounougal', 'Republic', 'Dakar'), ('SYC', 'Seychelles', 'Africa', 'Eastern Africa', '1976', 'Sesel/Seychelles', 'Republic', 'Victoria'), ('SLE', 'Sierra Leone', 'Africa', 'Western Africa', '1961', 'Sierra Leone', 'Republic', 'Freetown'), ('SGP', 'Singapore', 'Asia', 'Southeast Asia', '1965', 'Singapore/Singapura/Xinjiapo/Singapur', 'Republic', 'Singapore'), ('SVK', 'Slovakia', 'Europe', 'Eastern Europe', '1993', 'Slovensko', 'Republic', 'Bratislava'), ('SVN', 'Slovenia', 'Europe', 'Southern Europe', '1991', 'Slovenija', 'Republic', 'Ljubljana'), ('SOM', 'Somalia', 'Africa', 'Eastern Africa', '1960', 'Soomaaliya', 'Republic', 'Mogadishu'), ('LKA', 'Sri Lanka', 'Asia', 'Southern and Central Asia', '1948', 'Sri Lanka/Ilankai', 'Republic', 'Colombo'), ('SDN', 'Sudan', 'Africa', 'Northern Africa', '1956', 'As-Sudan', 'Islamic Republic', 'Khartoum'), ('FIN', 'Finland', 'Europe', 'Nordic Countries', '1917', 'Suomi', 'Republic', 'Helsinki'), ('SUR', 'Suriname', 'South America', 'South America', '1975', 'Suriname', 'Republic', 'Paramaribo'), ('SWZ', 'Swaziland', 'Africa', 'Southern Africa', '1968', 'kaNgwane', 'Monarchy', 'Mbabane'), ('CHE', 'Switzerland', 'Europe', 'Western Europe', '1499', 'Schweiz/Suisse/Svizzera/Svizra', 'Federation', 'Bern'), ('SYR', 'Syria', 'Asia', 'Middle East', '1941', 'Suriya', 'Republic', 'Damascus'), ('TJK', 'Tajikistan', 'Asia', 'Southern and Central Asia', '1991', 'Tocikiston', 'Republic', 'Dushanbe'), ('TZA', 'Tanzania', 'Africa', 'Eastern Africa', '1961', 'Tanzania', 'Republic', 'Dodoma'), ('DNK', 'Denmark', 'Europe', 'Nordic Countries', '800', 'Danmark', 'Constitutional Monarchy', 'Copenhagen'), ('THA', 'Thailand', 'Asia', 'Southeast Asia', '1350', 'Prathet Thai', 'Constitutional Monarchy', 'Bangkok'), ('TGO', 'Togo', 'Africa', 'Western Africa', '1960', 'Togo', 'Republic', 'Lome'), ('TON', 'Tonga', 'Oceania', 'Polynesia', '1970', 'Tonga', 'Monarchy', "Nuku'alofa"), ('TTO', 'Trinidad and Tobago', 'North America', 'Caribbean', '1962', 'Trinidad and Tobago', 'Republic', 'Port-of-Spain'), ('TCD', 'Chad', 'Africa', 'Central Africa', '1960', 'Tchad/Tshad', 'Republic', "N'Djamena"), ('CZE', 'Czech Republic', 'Europe', 'Eastern Europe', '1993', '¸esko', 'Republic', 'Prague'), ('TUN', 'Tunisia', 'Africa', 'Northern Africa', '1956', 'Tunis/Tunisie', 'Republic', 'Tunis'), ('TUR', 'Turkey', 'Asia', 'Middle East', '1923', 'Turkiye', 'Republic', 'Ankara'), ('TKM', 'Turkmenistan', 'Asia', 'Southern and Central Asia', '1991', 'Turkmenostan', 'Republic', 'Ashgabat'), ('TCA', 'Turks and Caicos Islands', 'North America', 'Caribbean', None, 'The Turks and Caicos Islands', 'Dependent Territory of the UK', 'Grand Turk'), ('TUV', 'Tuvalu', 'Oceania', 'Polynesia', '1978', 'Tuvalu', 'Constitutional Monarchy', 'Funafuti'), ('UGA', 'Uganda', 'Africa', 'Eastern Africa', '1962', 'Uganda', 'Republic', 'Kampala'), ('UKR', 'Ukraine', 'Europe', 'Eastern Europe', '1991', 'Ukrajina', 'Republic', 'Kiev'), ('HUN', 'Hungary', 'Europe', 'Eastern Europe', '1918', 'Magyarorszag', 'Republic', 'Budapest'), ('URY', 'Uruguay', 'South America', 'South America', '1828', 'Uruguay', 'Republic', 'Montevideo'), ('NCL', 'New Caledonia', 'Oceania', 'Melanesia', None, 'Nouvelle-Caledonie', 'Nonmetropolitan Territory of France', "Noum'ea"), ('NZL', 'New Zealand', 'Oceania', 'Australia and New Zealand', '1907', 'New Zealand/Aotearoa', 'Constitutional Monarchy', 'Wellington'), ('UZB', 'Uzbekistan', 'Asia', 'Southern and Central Asia', '1991', 'Uzbekiston', 'Republic', 'Tashkent'), ('BLR', 'Belarus', 'Europe', 'Eastern Europe', '1991', 'Belarus', 'Republic', 'Minsk'), ('VUT', 'Vanuatu', 'Oceania', 'Melanesia', '1980', 'Vanuatu', 'Republic', 'Port-Vila'), ('VEN', 'Venezuela', 'South America', 'South America', '1811', 'Venezuela', 'Federal Republic', 'Caracas'), ('RUS', 'Russian Federation', 'Europe', 'Eastern Europe', '1991', 'Rossija', 'Federal Republic', 'Moscow'), ('VNM', 'Vietnam', 'Asia', 'Southeast Asia', '1945', 'Viet Nam', 'Socialistic Republic', 'Hanoi'), ('EST', 'Estonia', 'Europe', 'Baltic Countries', '1991', 'Eesti', 'Republic', 'Tallinn'), ('USA', 'United States', 'North America', 'North America', '1776', 'United States', 'Federal Republic', 'Washington D.C.'), ('VIR', 'Virgin Islands, U.S.', 'North America', 'Caribbean', None, 'Virgin Islands of the United States', 'US Territory', 'Charlotte Amalie'), ('ZWE', 'Zimbabwe', 'Africa', 'Eastern Africa', '1980', 'Zimbabwe', 'Republic', 'Harare'), ('PSE', 'Palestine', 'Asia', 'Middle East', None, 'Filastin', 'Autonomous Area', None)]

You can make the output of the fetchall() method slightly prettier by iterating over each rows -

for row in cur.execute('SELECT * FROM countries'):
    print(row)
('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', '1919', 'Afganistan/Afqanestan', 'Islamic Emirate', 'Kabul')
('NLD', 'Netherlands', 'Europe', 'Western Europe', '1581', 'Nederland', 'Constitutional Monarchy', 'Amsterdam')
('ALB', 'Albania', 'Europe', 'Southern Europe', '1912', 'Shqiperia', 'Republic', 'Tirane')
...
('USA', 'United States', 'North America', 'North America', '1776', 'United States', 'Federal Republic', 'Washington D.C.')
('VIR', 'Virgin Islands, U.S.', 'North America', 'Caribbean', None, 'Virgin Islands of the United States', 'US Territory', 'Charlotte Amalie')
('ZWE', 'Zimbabwe', 'Africa', 'Eastern Africa', '1980', 'Zimbabwe', 'Republic', 'Harare')
('PSE', 'Palestine', 'Asia', 'Middle East', None, 'Filastin', 'Autonomous Area', None)

Let's now see how you add a where clause to the query and execute it. Let's fetch the details of the country where the code = 'AFG'.

code = ('AFG',)
cur.execute('SELECT * FROM countries WHERE code = ?', code)
print(cur.fetchone())
('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', '1919', 'Afganistan/Afqanestan', 'Islamic Emirate', 'Kabul')

You could have done the following also in order to get the records, but the above one is more secure.

code = 'AFG'
cur.execute("SELECT * FROM countries WHERE code = '%s'" % code)
print(cur.fetchone())
('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', '1919', 'Afganistan/Afqanestan', 'Islamic Emirate', 'Kabul')

You can insert records into a table either one by one or many records at one go. For this, let's use the consumers table. It does not contain any record as of now. Let's populate it from here.

# One by one
cur.execute("INSERT INTO consumers VALUES (1,'John Doe','john.doe@xyz.com','A')")
for row in cur.execute('SELECT * FROM consumers'):
    print(row)
(1, 'John Doe', 'john.doe@xyz.com', 'A')
# Prepare a list of records to be inserted
purchases = [(2,'John Paul','john.paul@xyz.com','B'),
             (3,'Chris Paul','john.paul@xyz.com','A'),
            ]

# Use executemany() to insert multiple records at a time
cur.executemany('INSERT INTO consumers VALUES (?,?,?,?)', purchases)
for row in cur.execute('SELECT * FROM consumers'):
    print(row)
(1, 'John Doe', 'john.doe@xyz.com', 'A')
(2, 'John Paul', 'john.paul@xyz.com', 'B')
(3, 'Chris Paul', 'john.paul@xyz.com', 'A')

You can cross-check this from the DB Browser tool, the records should reflect there as well. This will not happen until and unless you are committing these transactions. You can commit/save this by merely calling the commit() method of the Connection object you created.

conn.commit()

You should be able to see the entries now -

It is a good programming practice to close the DB connection once the works are done. But before that, the changes need to be made permanent, and it is achieved using the commit() method as shown above.

# Closing the DB connection
conn.close()

Congrats!

Thank you for reading through the entire tutorial. This tutorial introduced you to SQLite, a powerful but light-weighted RDBMS and you learned to interact with SQLite using Python. Let me know if you have any questions in the comments section.

If you would like to learn more about interacting with databases in Python, take DataCamp's Introduction to Databases in Python course.

Want to leave a comment?