问题描述
我试图将我的 json 文件数据插入到名为 location 的数据库表中,但无论我做什么它都不起作用,我一直在 mycursor.execute 中收到相同的错误,我是 Python 的初学者,所以我不知道很多 任何帮助将不胜感激,谢谢 多亏你,我解决了之前的问题,我忘了关闭 sql_location 中的括号
import MysqL.connector
import json
mydb = MysqL.connector.connect(host='localhost',port='3306',user='root',password='nihad147',database='tweets')
mycursor = mydb.cursor()
sql_location = """insert into tweet_location (
latitude,longitude,tweet_id,VALUES(%s,%s,%s)"""
myJsonFile = open('tweet.json',encoding="utf-8")
mycursor.execute("DELETE FROM tweet_location")
c = 0
for line in myJsonFile:
c = c + 1
print("tweet number ",c," is uploading to the server")
data = json.loads(line)
tweet = ("select * from tweet ")
mycursor.execute(tweet)
myresult = mycursor.fetchall()
row_count = len(myresult)
if row_count == 0:
val_location = (data['location']['lat'],data['location']['lon'],data['tweet_id'])
mycursor.execute(sql_location,val_location)
mydb.commit()
这是我不断收到的错误:
mycursor.execute(sql_location,val_location)
在执行 self._handle_result(self._connection.cmd_query(stmt)) 在 cmd_query 结果 = self._handle_result(self._send_cmd(ServerCmd.QUERY,query)) 在 _handle_result 中引发 errors.get_exception(packet)
MysqL.connector.errors.ProgrammingError: 1064 (42000): 你的 sql 语法有错误;检查与您的 MysqL 服务器版本相对应的手册,以获取在第 5 行的 'VALUES(28.0000272,2.9999825,'1298045077621800960')' 附近使用的正确语法
我的json文件数据示例:
{
"tweet_id": "1261276320878788609","date": "Fri May 15 12:44:42 +0000 2020","raw_text": "برنامج وطني لدعم المبدعين في مواجهة #كورونا","geo_source": "user_location","location": {
"address": {
"country": "Tunisia","country_code": "tn","state_district": "غزالة","county": "العرب","state": "Bizerte"
},"response": "{'place_id': 235309103,'licence': 'Data © OpenStreetMap contributors,ODbL 1.0. https://osm.org/copyright','osm_type': 'relation','osm_id': 7124228,'boundingBox': ['37.105957','37.2033466','9.4739053','9.6124953'],'lat': '37.1551868','lon': '9.54834183807249','display_name': 'العرب,غزالة,Bizerte,Tunisia','class': 'boundary','type': 'administrative','importance': 0.45,'icon': '/data/nominatimimages/mapicons/poi_boundary_administrative.p.20.png','address':{'county': 'العرب','state_district': 'غزالة','state': 'Bizerte','country': 'Tunisia','country_code': 'tn'}}","geohash": "snwg37buskzd","query_term": "arab","lon": 9.54834183807249,"lat": 37.1551868
},"user_friends_count": 61,"user_description": "I love UAE and his great leadership","user_created_at": "Wed Oct 09 11:41:41 +0000 2013","user_screen_name": "SikandarMirani","user_id_str": "706377881","user_verified": false,"user_statuses_count": 50804,"user_followers_count": 946,"user_location": "dubai United arab Emirates"
}
我将我的数据库表声明为 tweet_id bigint / 纬度浮点数 / 经度浮点数
解决方法
您尚未关闭变量 sql_location
中的括号。
应该是:
sql_location = """insert into tweet_location (latitude,longitude,tweet_id) values (%s,%s,%s)