python脚本插入MySQL数据库-特殊符号-unicode:搜索和存储


python script to insert into MySQL database - special symbols - unicode : search and store

我想知道将''alpha等符号编码到MySQL数据库中并有效查询它的最佳策略是什么。

我使用"CHARSET=utf8"创建MySQL表。

import mysql.connector
import urllib
import re
from mysql.connector import errorcode
Connection = mysql.connector.connect(user='XXXX', password='XXXX', unix_socket="mysql.sock")
Cursor = Connection.cursor()
Cursor.execute('''CREATE TABLE IF NOT EXISTS `test` (
            `test_string` text NOT NULL,
            `id` int(5) NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `id` (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            ''')
 xml = unicode(urllib.urlopen('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&id=2174229').read(),'utf-8')
 Cursor.execute('''INSERT INTO `test` (`id`, `test_string`) VALUES ('''+"001"+", '"+re.escape(xml).encode("utf-8")+"');")

接下来,当编码字符串时,在将它们插入MySQL数据库之前,我确保使用".encode("utf-8")"将它们编码到utf8中,并且在插入时,我确保在插入之前使用"re.eescape"转义字符串。

接下来,我进入phpMyAdmin查看数据行,例如

原始字符串是

"generating the α- and β-APP", 

插入后,在数据库中我可以将其视为

"generating the α- and β-APP"

但是,如果我在html页面上查询数据库中包含"生成"的行后显示,则符号α和β将正确显示在html页面上。我很困惑。

为什么会这样?我有一个相关的问题是,现在如果我必须在MySQL数据库中查询这些特殊符号(α、β等),我该怎么做?如果我遗漏了任何明显的问题,请原谅。

尝试以下操作:

(user='XXXX', password='XXXX', unix_socket="mysql.sock",charset='utf8',use_unicode=True)

然后转到phpmyadmin并更改排序规则utf8_general_ci。

好的,最后的问题是特殊字符以某种方式转换为HTML代码。所以,做到了

import HTMLParser
h= HTMLParser.HTMLParser()
h.unescape(test_string)