python - Converting MSSQL database to GeoJSON format
问题描述
I'm trying to use Python to access an MSSQL database and then write the results out to a GeoJSON file. So far I have this code, but I can't get a working end part which saves the file to my directory
import pandas as pd
import pyodbc
import geojson
import json
from geojson import Feature, FeatureCollection, Point
conn = pyodbc.connect('Driver={SQL Server};'
'Server=LAPTOP;'
'Database=WB;'
'Trusted_Connection=yes;')
sql_query = pd.read_sql_query('''
select * from WB.dbo.Transactions
'''
,conn) # here, the 'conn' is the variable that contains your database connection information from step 2
df = pd.DataFrame(sql_query)
def df_to_geojson(df, properties, lat='latitude', lon='longitude'):
geojson = {'type':'FeatureCollection', 'features':[]}
for _, row in df.iterrows():
feature = {'type':'Feature',
'properties':{},
'geometry':{'type':'Point',
'coordinates':[]}}
feature['geometry']['coordinates'] = [row[lon],row[lat]]
for prop in properties:
feature['properties'][prop] = row[prop]
geojson['features'].append(feature)
return geojson
I've tried the following to save it to an output file, but it throws up an error that GeoJSON is a module not a string - so I changed the above code from geojson to geojson1 and then it comes up that geojson1 isn't defined
with open('C:/Users/Public/Documents/transactions.geojson', 'w') as f:
f.write(geojson)
解决方案
尝试在将 json.dump(geojson) 写入文件之前添加它。此外,您不应在第 3 行和第 5 行两次导入模块。
推荐阅读
- reactjs - react 说 Error: Invalid hook call when I try to use material makestyles
- sql - 使用数据库链接时在多个条件下进行内连接
- android - 保存片段状态导航组件JAVA
- python - Python Selenium - 数据不可见;没有错误
- javascript - 画布上下文上的多个填充():rgba透明颜色改变
- excel - Excel 动态数组 - 可能的错误?
- javascript - 不随页面刷新的计数器
- swiftui - SwiftUI 从 UITextField 中关闭键盘
- image - 如何将图像添加到 Go 中的特定文件夹中?收到类似错误:`%!(EXTRA *fs.PathError=open /photos: read-only file system)`
- html - 即使我已经很好地计算了网格系统(引导程序),列也不会粘在一起