使用Python将JSON插入MySQL
我在Python中有一个JSON对象。我正在使用Python DB-API和SimpleJson。我正在尝试将json插入MySQL表中 目前我遇到了一些错误,我相信这是由于JSON对象中的单引号造成的 如何使用Python将JSON对象插入MySQL 以下是我收到的错误消息:使用Python将JSON插入MySQL,python,mysql,json,python-db-api,Python,Mysql,Json,Python Db Api,我在Python中有一个JSON对象。我正在使用Python DB-API和SimpleJson。我正在尝试将json插入MySQL表中 目前我遇到了一些错误,我相信这是由于JSON对象中的单引号造成的 如何使用Python将JSON对象插入MySQL 以下是我收到的错误消息: error: uncaptured python exception, closing channel <twitstream.twitasync.TwitterStreamPOST connected at
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
错误:未捕获的python异常,正在关闭通道
(:
(1064),“您的SQL语法有错误;请检查
与您的MySQL服务器版本相对应的手册
要在“favorited”附近使用的正确语法:“0”,
“在用户id的回复中”:“52063869”,“贡献者”:
“空”、“第1行的tr”)
[/usr/lib/python2.5/asyncore.py | read | 68]
[/usr/lib/python2.5/asyncore.py | handle | read | event | 390]
[/usr/lib/python2.5/asynchat.py | handle|u read | 137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py | found | terminator | 55][twitter.py | callback | 26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py | execute | 166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py | defaulterrorhandler | 35])
另一个错误供参考
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
错误:未捕获的python异常,正在关闭通道
(:
(1064),“您的SQL语法有错误;请检查手册
对应于右边的MySQL服务器版本
使用near'RT@tweetmeme最佳黑莓珍珠的语法
手机套http://bit.ly/9WtwUO“第1行中的”一词)
[/usr/lib/python2.5/asyncore.py | read | 68]
[/usr/lib/python2.5/asyncore.py | handle | read | event | 390]
[/usr/lib/python2.5/asynchat.py | handle|u read | 137]
[/usr/lib/python2.5/site packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py | found|u terminator | 55]
[twitter.py | callback | 28][build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py | execute | 166][build/bdist.linux-
x86_64/egg/MySQLdb/connections.py | defaulterrorhandler | 35])
下面是我正在使用的代码的链接
#/usr/bin/env python
尝试:
将json作为simplejson导入
除恐怖外:
导入simplejson
导入推流
导入MySQLdb
用户=“”
通过=“”
用法=“程序”
conn=MySQLdb.connect(主机=”,
用户=”,
passwd=“”,
db=”“)
#定义一个可在每个状态下调用的函数/可调用函数:
def回调(状态):
twitdb=conn.cursor()
twitdb.execute(“插入到tweets_未处理(文本、创建的_at、twitter_id、用户id、用户屏幕名称、json)值(%s、%s、%s、%s)”,(status.get('text')、status.get('created_at')、status.get('id')、status.get('user'、{}.get('id')、status.get('user'、{}.get('user'))、get({}.get('screen\u name')、status))
#打印状态
#打印“%s:\t%s\n”%(status.get('user',{}).get('screen_name')、status.get('text'))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#从twitstream模块调用特定的API方法:
#stream=twitstream.spritzer(用户、传递、回调)
twitstream.parser.usage=用法
(options,args)=twitstream.parser.parse_args()
如果len(args)<1:
args=['Blackberry']
stream=twitstream.track(用户、传递、回调、参数、options.debug、引擎=options.engine)
#在流式通话中永久循环:
stream.run()
该错误可能是由于尝试插入json的字段大小溢出所致。没有任何代码,很难帮助您
您考虑过像couchdb这样的无sql数据库系统吗?couchdb是一种基于json格式的面向文档的数据库。您应该能够轻松地在intyo中插入文本或blob列
db.execute("INSERT INTO json_col VALUES %s", json_value)
要扩展其他答案,请执行以下操作: 基本上,您需要确保两件事:
# Simple, but naive, method.
# Notice that you are passing in 1 large argument to db.execute()
db.execute("INSERT INTO json_col VALUES (" + json_value + ")")
更好的方法是使用:
# Correct method. Uses parameter/bind variables.
# Notice that you are passing in 2 arguments to db.execute()
db.execute("INSERT INTO json_col VALUES %s", json_value)
希望这有帮助。如果是,请告诉我:-)
如果您仍然有问题,那么我们需要更仔细地检查您的语法。您需要查看实际的SQL字符串,请尝试以下操作:
sqlstr = "INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)", (status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status)
print "about to execute(%s)" % sqlstr
twitdb.execute(sqlstr)
我想您会在其中找到一些不正确的引号、括号或括号。使用json.dumps(json_值)将json对象(python对象)转换为json字符串,您可以将其插入mysql的文本字段中
将python映射插入MySQL JSON字段的最简单方法
python_map = { "foo": "bar", [ "baz", "biz" ] }
sql = "INSERT INTO your_table (json_column_name) VALUES (%s)"
cursor.execute( sql, (json.dumps(python_map),) )
这里有一个快速提示,如果您想编写一些内联代码,比如一个小的json值,而不需要
导入json
。
您可以通过双引号在SQL中转义引号,即使用'
或'
,输入'
或'
Python代码示例(未测试):
例如,如何使用
Python
将JSON
文件添加到MySQL
中。这意味着有必要将JSON
文件转换为sqlinsert
,如果有多个JSON
对象,那么最好只调用一个insert
,而不是多次调用,即每个对象都调用c将所有功能插入
#导入Python的JSON库
导入json
#使用JSON加载创建记录列表
test_json=json.load(“”)
[
{
“COL_ID”:“id1”,
“COL_INT_VAULE”:7,
“COL_BOOL_VALUE”:正确,
“COL_FLOAT_VALUE”:3.14159,
“列字符串值”:“堆栈溢出应答”
},
{
“COL_ID”:“id2”,
“COL_INT_VAULE”:10,
“COL_BOOL_VALUE”:false,
“COL_FLOAT_VALUE”:2.7182
@route('/shoes', method='POST')
def createorder():
cursor = db.cursor()
data = request.json
p_id = request.json['product_id']
p_desc = request.json['product_desc']
color = request.json['color']
price = request.json['price']
p_name = request.json['product_name']
q = request.json['quantity']
createDate = datetime.now().isoformat()
print (createDate)
response.content_type = 'application/json'
print(data)
if not data:
abort(400, 'No data received')
sql = "insert into productshoes (product_id, product_desc, color, price, product_name, quantity, createDate) values ('%s', '%s','%s','%d','%s','%d', '%s')" %(p_id, p_desc, color, price, p_name, q, createDate)
print (sql)
try:
# Execute dml and commit changes
cursor.execute(sql,data)
db.commit()
cursor.close()
except:
# Rollback changes
db.rollback()
return dumps(("OK"),default=json_util.default)
python_map = { "foo": "bar", [ "baz", "biz" ] }
sql = "INSERT INTO your_table (json_column_name) VALUES (%s)"
cursor.execute( sql, (json.dumps(python_map),) )
q = 'INSERT INTO `table`(`db_col`) VALUES ("{k:""some data"";}")'
db_connector.execute(q)