Log4Classicning

好读书 不求甚解 每有会意 便欣然忘食

用Python脚本将shp导入mysql
2008年3月4日

前天数字化完校园地图后,面对几个shp文件忽然有一种一筹莫展的感觉。以前都是用Geotools将shp转到mysql中,但是运行起来很麻烦,光是netBeans就要启动很长时间。

于是想起来利用ogr和MySQLdb这两个Python库,写一个简单的脚本来实现这个过程,也算是熟悉一下ogr库的用法。仔细一看,ogr大约也是走OpenGIS的相关标准,定义了Layer、Feature等相关的名词。

以下是代码片段,文档不好找,希望对读者有帮助吧

from osgeo import ogr
def insertion(f, curs):
    global c
    g = ogr.Open(f)
    l = g.GetLayer(0)

    for i in range(l.GetFeatureCount()):
        f = l.GetFeature(i)
        name = unicode(f.GetFieldAsString("name"),"GBK").encode("utf8")
        wkt = str(f.GetGeometryRef())
        params = "null, GeomFromText('%s'),'%s','',0,0,%d"% (wkt,name,c)
        sql = 'insert into '+tablename+' values(%s);'%params
        print sql
        fsql.write(sql)
        fsql.write('\n')
        c = c+1
        curs.execute(sql)


« 基于GeoServer/OpenLayers/MySQL的校园地图上线测试 初试Wicket »
  • quote 1.co2
  • 藏之
    开始学python中的数据库操作了
    mysql postgresql
    不知道哪个用在GIS上更方便些?
  • 2008-3-7 21:58:37 回复该留言

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Search

站点统计

  • 文章总数:745
  • 评论总数:2630
  • 引用总数:4
  • 浏览总数:5693
  • 留言总数:42
  • 当前主题:ClassicningDailyLog Style
  • 当前样式:footoo

网站收藏

图标汇集

  • Creative Commons License
  • Widgetize!
  • visitor stats

Powered By Z-Blog 1.8 Spirit Build 80722

2004 - 2007 Classicning.com. 苏ICP备06039259号.