我无法在sql中插入一些文本,我想知道如何处理该字符串,以便它被接受。
无法编辑json文件,因为文件太大。
这是我得到的错误:
Traceback (most recent call last):
File "test.py", line 31, in <module>
main()
File "test.py", line 28, in main
cursor.execute("""insert into test_table (text) values (%s)""", (text,))
File "../dependencies/mysql/connector/cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "../dependencies/mysql/connector/connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "../dependencies/mysql/connector/connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.DataError: 1366 (22007): Incorrect string value: '\xE2\x88\x922: ...' for column 'text' at row 1
test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../dependencies'))
import json
import mysql.connector
def get_value_from_key(row, key):
return row.get(key)
def main():
json_path = "test.json"
db_connection = mysql.connector.connect(host="localhost", user='root', password='root')
cursor = db_connection.cursor()
db_name = 'test'
cursor.execute("DROP DATABASE IF EXISTS " + db_name)
cursor.execute("CREATE DATABASE " + db_name)
cursor.execute("USE " + db_name)
json_data = json.load(open(json_path, 'r'))
cursor.execute("""create table test_table (id integer AUTO_INCREMENT,PRIMARY KEY (id),
text text);""")
db_connection.commit()
text = get_value_from_key(json_data, "text")
cursor.execute("""insert into test_table (text) values (%s)""", (text,))
if __name__ == "__main__":
main()
test.json
{
"text": "+1: Create a 1/1 black Vampire creature token with lifelink.\n−2: You get an emblem with \"Creatures you control get +1/+0.\"\n−6: Destroy up to three target creatures and/or other planeswalkers. Return each card put into a graveyard this way to the battlefield under your control."
}
答案 0 :(得分:0)
就是这个
cursor.execute("CREATE DATABASE " + db_name + " DEFAULT CHARACTER SET utf8")