【发布时间】:2021-03-12 11:43:38
【问题描述】:
我正在尝试使用 Python 访问 MSSQL 数据库,然后将结果写入 GeoJSON 文件。 到目前为止,我有这段代码,但我无法获得将文件保存到我的目录的工作端部分
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
我尝试了以下方法将其保存到输出文件中,但它抛出了一个错误,即 GeoJSON 是一个模块而不是一个字符串 - 所以我将上面的代码从 geojson 更改为 geojson1 然后它出现了 geojson1 是'未定义
with open('C:/Users/Public/Documents/transactions.geojson', 'w') as f:
f.write(geojson)
【问题讨论】: