在windows环境下使用Python操作spatialite数据库

来源:互联网 发布:大唐麻将辅助软件 编辑:程序博客网 时间:2024/05/21 11:32

Spatialite是Sqlite的空间数据库扩展。在网上查了些资料,Python目前自带了sqlite模块,操作spatialite需要使用pyspatilite模块。但是在Windows下使用easy_install或者pip直接安装这个模块总是出错。因此参考这里下载配置了spatialite的DLL,然后使用“SELECT load_extension()”加载DLL从而通过python操作spatialite

import sqlite3# 连接数据库conn = sqlite3.connect(":memory:")conn.enable_load_extension(True)cur = conn.cursor()# 加载spatialite DLLcur.execute(r'SELECT load_extension("C:\Spatialite32\libspatialite-4.dll");')# 创建数据库表sql_create_table = r'Create Table test_geom(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);'cur.execute(sql_create_table)# 创建空间元数据表(开始没有做这个操作,导致后来几何列一直加不进数据表中)cur.execute('SELECT InitSpatialMetaData();')# 创建几何列sql_add_geom = r"Select AddGeometryColumn('test_geom', 'the_geom', 4326, 'POINT', 'XY', 1);"cur.execute(sql_add_geom)# 加入数据sql_insert = r"Insert into test_geom(the_geom, name, id) VALUES(GeomFromText('POINT(1.0 2.0)', 4326), 'my point', NULL);"cur.execute(sql_insert)conn.commit()# 查询cur.execute(r'select AsText(the_geom) from test_geom;')for item in cur.fetchall():    for element in item:        print element,    print# 关闭数据库conn.close()del conn


0 0