使用 PostgreSQL 存储数据
在本节中,我们将地球数据存储在 PostgreSQL 中。 PostgreSQL 是一个开源关系数据库管理系统(RDBMS)。 它由全球志愿者团队开发,不受任何公司或其他私人实体控制,并且源代码免费提供。 它具有许多独特的功能,例如分层数据模型。
准备工作
首先确保您有权访问 PostgreSQL 数据实例。 同样,您可以在本地安装一个,在容器中运行一个,或者在云中获取一个实例。
与MySQL 一样,我们需要首先创建一个数据库。 该过程与 MySQL 几乎相同,但命令和参数略有不同。
-
从终端执行 psql 命令。 这将带您进入 psql 命令处理器:
# psql -U postgres psql (9.6.4) Type "help" for help. postgres=#
-
现在创建抓取数据库:
postgres=# create database scraping; CREATE DATABASE postgres=#
-
然后切换到新数据库:
postgres=# \connect scraping You are now connected to database "scraping" as user "postgres". scraping=#
-
现在我们可以创建 Planets 表。 我们首先需要创建一个序列表:
scraping=# CREATE SEQUENCE public."Planets_id_seq" scraping-# INCREMENT 1 scraping-# START 1 scraping-# MINVALUE 1 scraping-# MAXVALUE 9223372036854775807 scraping-# CACHE 1; CREATE SEQUENCE scraping=# ALTER SEQUENCE public."Planets_id_seq" scraping-# OWNER TO postgres; ALTER SEQUENCE scraping=#
-
现在我们可以创建表:
scraping=# CREATE TABLE public."Planets" scraping-# ( scraping(# id integer NOT NULL DEFAULT nextval('"Planets_id_seq"'::regclass), scraping(# name text COLLATE pg_catalog."default" NOT NULL, scraping(# mass double precision NOT NULL, scraping(# radius double precision NOT NULL, scraping(# description text COLLATE pg_catalog."default" NOT NULL, scraping(# moreinfo text COLLATE pg_catalog."default" NOT NULL, scraping(# CONSTRAINT "Planets_pkey" PRIMARY KEY (name) scraping(# ) scraping-# WITH ( scraping(# OIDS = FALSE scraping(# ) </span>scraping-# TABLESPACE pg_default; CREATE TABLE scraping=# scraping=# ALTER TABLE public."Planets" scraping-# OWNER to postgres; ALTER TABLE scraping=# \q
要从 Python 访问 PostgreSQL,我们将使用 psycopg2 库,因此请确保使用 pip install psycopg2 将其安装在您的 Python 环境中。
我们现在准备编写 Python 将行星数据存储在 PostgreSQL 中。
怎么做
我们按如下方式继续示例:
-
以下代码将读取行星数据并将其写入数据库(03/save_in_postgres.py 中的代码):
import psycopg2 from get_planet_data import get_planet_data try: # connect to PostgreSQL conn = psycopg2.connect("dbname='scraping' host='localhost' user='postgres' password='mypassword'") # the SQL INSERT statement we will use insert_sql = ('INSERT INTO public."Planets"(name, mass, radius, description, moreinfo) ' + 'VALUES (%(Name)s, %(Mass)s, %(Radius)s, %(Description)s, %(MoreInfo)s);') # open a cursor to access data cur = conn.cursor() # get the planets data and loop through each planet_data = get_planet_data() for planet in planet_data: # write each record cur.execute(insert_sql, planet) # commit the new records to the database conn.commit() cur.close() conn.close() print("Successfully wrote data to the database") except Exception as ex: print(ex)
-
如果成功您将看到以下内容:
Successfully wrote data to the database
-
使用 pgAdmin 等 GUI 工具,您可以检查数据库中的数据:
-
可以使用以下 Python 代码查询数据(在 03/read_from_postgresql.py 中找到):
import psycopg2 try: conn = psycopg2.connect("dbname='scraping' host='localhost' user='postgres' password='mypassword'") cur = conn.cursor() cur.execute('SELECT * from public."Planets"') rows = cur.fetchall() print(rows) cur.close() conn.close() except Exception as ex: print(ex)
-
并产生以下输出(稍微截断:
[(1, 'Mercury', 0.33, 4879.0, 'Named Mercurius by the Romans because it appears to move so swiftly.', 'https://en.wikipedia.org/wiki/Mercury_(planet)'), (2, 'Venus', 4.87, 12104.0, 'Roman name for the goddess of love. This planet was considered to be the brightest and most beautiful planet or star in the heavens. Other civilizations have named it for their god or goddess of love/war.', 'https://en.wikipedia.org/wiki/Venus'), (3, 'Earth', 5.97, 12756.0, "The name Earth comes from the IndoEuropean base 'er,'which produced the Germanic noun 'ertho,' and ultimately German 'erde,' Dutch 'aarde,' Scandinavian 'jord,' and English 'earth.' Related forms include Greek 'eraze,' meaning 'on the ground,' and Welsh 'erw,' meaning 'a piece of land.'", 'https://en.wikipedia.org/wiki/Earth'), (4, 'Mars', 0.642, 6792.0, 'Named by the Romans for their god of war because of its red, bloodlike color. Other civilizations also named this planet from this attribute; for example, the Egyptians named it
工作原理
像我们一样使用 psycopg2 库访问 PostgreSQL 数据库涉及到使用该库中的两个类:connect 和cursor。 connect 类打开并管理与数据库服务器的连接。 从该连接对象中,我们可以创建一个光标对象。 该游标用于使用 SQL 语句读取和写入数据。
在第一个示例中,我们使用游标将九条记录插入数据库。 在调用连接的 commit() 方法之前,这些记录不会写入数据库。 这会将所有行写入数据库。
读取数据使用类似的模型,只不过我们使用游标执行 SQL 查询 (SELECT) 并迭代检索到的行。 由于我们正在读取而不是写入,因此无需在连接上调用 commit()。
还有更多
有关 PostgreSQL 的信息可在 https://www.postgresql.org/ 上获取。 pgAdmin 可以从以下网址获取: https://www.pgadmin.org/psycopg 的参考资料位于: http://initd.org/psycopg/docs/usage.html