H5W3
当前位置:H5W3 > 其他技术问题 > 正文

Python中的SQLite用法指南

本文概述

关系数据库管理系统(RDBMS)非常流行, 并且是应用程序开发中不可或缺的一部分。存在许多不同的RDBMS, 例如MySQL, PostgreSQL, IBM DB2, Oracle 11g等。这样的RDBMS是SQLite。 SQLite被广泛使用, 由于许多原因而受到开发人员的喜爱-

  • 重量极轻(不超过500 KB)
  • 它是无服务器的, 这意味着你不需要任何单独的服务器即可使用其服务
  • 无需复杂的设置
  • 完全符合交易和并发性
  • 还有很多…

但是, SQLite也有一些限制。例如, 它不支持RIGHT OUTER JOIN和FULL OUTER JOIN之类的联接。但是优势远不止局限。在本教程中, 将向你介绍如何在Python中使用SQLite, 以下是本教程涵盖的内容概述-

  • SQLite的安装和设置
  • 在SQLite中创建数据库和表
  • 将.csv文件导入SQLite数据库
  • Python中的SQLite

注意:本教程假定你已经熟悉SQL(使用任何RDBMS)和Python(3)的基础知识。如果你想重新掌握这些技能, 可以使用以下资源-

  • Python简介
  • srcmini的SQL for Data Science简介

一旦你对使用SQL和Python感到满意, 就可以返回并从上次中断的地方继续。

安装与设定

安装和设置SQLite只需几分钟。你可以从命令行工具使用SQLite, 但是有一个基于GUI的实用程序, 可让你通过不错的图形界面使用SQLite。对于本教程, 你将使用DB Browser for SQLite。首先, 你将首先从此处根据你的OS平台下载此工具。

在Windows 7平台上, DBite for SQLite的界面如下所示-

Python中的SQLite1

创建数据库和表

一旦准备好使用数据库浏览器工具, 就可以创建一个新的SQLite数据库以继续进行。为此, 你可以点击”新建数据库”标签-

Python中的SQLite2

单击”新建数据库”选项卡后, 将提示你输入数据库的名称。输入你选择的名称, 然后继续。你输入的名称的空数据库将立即创建, 并提示你在该数据库下创建表。你可以跳过表创建部分, 现在, 你将很快进入。

要创建表, 你需要修复表的架构。为了便于学习和理解本教程, 我们首先创建一个简单的表, 名称为consumers, 具有以下字段和数据类型-

  • Consumer_id(整数)
  • Consumer_full_name(字符串)(不能为null)
  • Consumer_email(字符串)(不能为null)
  • Consumer_grade(字符)(不能为null)

注意:如果你熟悉数据库架构设计, 则可能会想起consumer_id字段是表的主键(这就是为什么带下划线的原因)。

要创建表格, 请点击创建表格标签, 系统会提示你输入要创建的表格的详细信息-

Python中的SQLite3

如果仔细观察上图, 你会发现它包含了你希望合并到表使用者中的确切详细信息。你还可以查看创建表的相应SQL。数据库浏览器工具使你可以非常高效地执行此操作。按照此步骤操作后, 单击”确定”按钮, 表使用者应该出现在你有时创建的数据库下-

Python中的SQLite4

之所以存在表sqlite_sequence, 是因为如果你指定了consumer_id字段为自动递增的, 则SQLite将创建一个单独的表来维护序列。你还可以通过转到执行SQL部分来执行其他SQL查询。随意执行一些你喜欢的SQL查询。

现在, 在使用Python与SQLite数据库进行交互之前, 让我们看看如何将.csv文件导入SQLite数据库并将其用于分析。

将.csv文件导入SQLite数据库

要将.csv文件导入你创建的数据库, 只需遵循以下导航:File-> Import-> Table from CSV file。你可以为此目的使用此.csv文件。它包含有关全球不同国家的详细信息。导航到该文件, 然后你将看到如下对话框:

Python中的SQLite5

使用数据库浏览器, 你可以在此处指定许多内容, 包括表的名称。确保选中第一行中的列名选项, 以便SQLite可以自动提取列名。完成规格后, 单击”确定”。

你应该能够看到该表的条目-

Python中的SQLite6

随时执行一些选择查询, 以查看表是否正确导入。

Python中的SQLite

现在, 你已经可以使用数据库和表。为了能够使用Python与SQLite数据库进行交互, 你将需要Anaconda发行版随附的sqlite3模块。

现在, 你将使用sqlite3提供的connect()方法连接到你创建的数据库。这将返回一个Connection对象。将数据库的路径提供给connect方法。数据库通常以.db扩展名保存。

import sqlite3

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

与数据库建立连接后, 可以创建一个Cursor对象并调用其execute()方法以执行SQL命令。

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

执行SELECT语句后, 你可以-

  • 将光标对象cur视为迭代器, 调用fetchone()方法显示单行或
  • 调用fetchall()方法以显示行列表

让我们一一尝试。

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)]

你可以通过遍历每行来使fetchall()方法的输出更美观-

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)

现在让我们看看如何向查询添加where子句并执行它。让我们获取代码=” 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')

你也可以执行以下操作以获得记录, 但是以上记录更加安全。

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')

你可以一次将记录一条一张或多条插入一张表。为此, 让我们使用消费者表。到目前为止, 它不包含任何记录。让我们从这里填充它。

# 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')

你可以通过数据库浏览器工具对此进行交叉检查, 记录也应在此处反映出来。除非并且除非提交这些事务, 否则这不会发生。你可以仅通过调用所创建的Connection对象的commit()方法来提交/保存该文件。

conn.commit()

你现在应该可以看到条目-

Python中的SQLite7

完成工作后, 关闭数据库连接是一种良好的编程习惯。但是在此之前, 需要使更改永久生效, 并且可以使用上述的commit()方法来实现。

# Closing the DB connection
conn.close()

恭喜!

感谢你阅读整个教程。本教程向你介绍了SQLite, 它是功能强大但轻量级的RDBMS, 并且你学习了如何使用Python与SQLite进行交互。如果你在评论部分有任何疑问, 请告诉我。

如果你想了解有关使用Python与数据库交互的更多信息, 请参加srcmini的Python数据库简介课程。

本文地址:H5W3 » Python中的SQLite用法指南

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址