gpt4 book ai didi

php - 用于插入 MySQL 数据库的 python 脚本 - 特殊符号 - unicode : search and store

转载 作者:行者123 更新时间:2023-11-29 23:34:11 33 4
gpt4 key购买 nike

我想知道将\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.escape”对字符串进行转义插入。

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

原始字符串是

"generating the α- and β-APP", 

插入后,在数据库中我可以看到它为

"generating the α- and β-APP"

但是,如果我在 html 页面上从数据库查询包含“generate the”的行后显示,则符号 α 和 β 会正确显示在 HTML 页面上。我很困惑。

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

最佳答案

尝试以下操作:

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

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

关于php - 用于插入 MySQL 数据库的 python 脚本 - 特殊符号 - unicode : search and store,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26439606/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com