import sqlite3 as sqlite
db = sqlite.connect(':memory:')
db.enable_load_extension(True)
db.execute('SELECT load_extension("mod_spatialite")')
<sqlite3.Cursor at 0x7f606f58b340>
注意,上面执行 SQL 语句时,返回了一些信息,但这些信息对于学习是没有用的。 在下面的章节中,对于此类信息,不在文中出现,使用的时候要注意。
注,因为SQLite是无服务器数据库,
myDatabase.db
数据库就像硬盘上的文件。 如果在Mac操作系统上运行,可以略过enable_load_extension
,load_extension
。
这个需要进行初始化。否则,会出现下面的错误。
AddGeometryColumn() error: unexpected metadata layout
另外, Python 2中有 pyspatialite 模块, 可以简化一些操作。但是,这个模块最后一次更新时间是 2013 年,并且不支持 Python 3, 所以在本书中就不做介绍了。使用 Python 2 的话可以了解一下。
cursor = db.cursor()
# cursor.execute('drop table if exists spatial_ref_sys ')
# cursor.execute('drop table if exists geometry_columns ')
# cursor.execute('drop view if exists geom_cols_ref_sys ')
# cursor.execute('drop table if exists SpatialIndex ')
# cursor.execute('drop table if exists ElementaryGeometries ')
# cursor.execute('drop table if exists KNN2 ')
cursor.execute('SELECT InitSpatialMetaData();')
<sqlite3.Cursor at 0x7f606c3b95c0>
cursor.execute("DROP TABLE IF EXISTS cities")
<sqlite3.Cursor at 0x7f606c3b95c0>
cursor.execute("CREATE TABLE cities (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name CHAR(255))")
<sqlite3.Cursor at 0x7f606c3b95c0>
然后,用SpatiaLite的AddGeometryColumn()
函数来定义表格中的空间列。
cursor.execute("SELECT AddGeometryColumn('cities', 'geom', 4326, 'POLYGON', 2)")
<sqlite3.Cursor at 0x7f606c3b95c0>
4326是用来识别列属性的空间参照ID(SRID),是用经纬度和WGS84来定义的空间参照。
可以用 CreateSpatialIndex()
函数来创建几何对象中的空间索引。如下:
cursor.execute("SELECT CreateSpatialIndex('cities', 'geom')")
<sqlite3.Cursor at 0x7f606c3b95c0>
已经创建了数据库表格,用 GeomFromText()
功能插入几何对象的属性。
cursor.execute("INSERT INTO cities (name, geom)" + \
" VALUES ({0}, GeomFromText({1}, 4326))".format('"city"', '"wkt"'))
<sqlite3.Cursor at 0x7f606c3b95c0>
cursor.execute('select name, astext(geom) from cities')
for x in cursor.fetchall():
print(x)
# print(name,wkt)
('city', None)