gpt4 book ai didi

mysql - 无法在 Perl 中使用 DBI 在 mysql 中插入变音符号文本的等效纯文本

转载 作者:行者123 更新时间:2023-11-29 14:14:53 24 4
gpt4 key购买 nike

我有一列是我的表的主键,它可以包含变音符号或普通文本。

我有这两个值:

Håbo and Habo

我想在表中插入这两列值,但出现错误:

DBD::mysql::st execute failed: Duplicate entry 'Habo' for key 'PRIMARY'

当我检查 Håbo 已插入时,它会将两个值视为相同,因此主键违规。

我的代码:

$dbh = DBI->connect($dsn, $user, $pass)
or die "Unable to connect: $DBI::errstr\n";
$dbh->{'mysql_enable_utf8'}=1;
$dbh->do('SET NAMES utf8');
my $sql = sprintf "INSERT INTO search_term values(%s, %s)", $dbh->quote($search_term), "Data";

我的表格描述

mysql> desc search_term;
+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| search | varchar(200) | NO | PRI | NULL | |
| site | varchar(500) | NO | | NULL | |
+---------------+--------------+------+-----+---------+-------+

如何让 MySQL 将两个值视为不同的值并插入它们?有什么建议吗?

最佳答案

默认情况下,MySQL "helpfully" converts Unicode into their "equivalent" ASCII使用名为 Unicode Collation 的东西。就像 MySQL 中的许多“方便”功能一样,如果它告诉你的话,就会方便得多。我无法在这些“单词”周围添加足够的“引号”。

幸运的是,修复非常简单,但并不明显。第一,change the character set of your tables to UTF8所以文本以utf8存储。然后change the collation to utf8_bin所以比较会准确进行。我不是 100% 确定 utf8_bin 是 100% 正确的东西,但它有效。

ALTER TABLE search_term CONVERT TO CHARACTER SET utf8;
ALTER TABLE search_term COLLATE utf8_bin;

以后在MySQL中建表时,一定要append CHARACTER SET utf8 to the creation .

CREATE TABLE search_term (
search varchar(200) primary key,
site varchar(500)
)
CHARACTER SET utf8
COLLATE utf8_bin;

最后,您不必对每个表都执行此操作,您可以 create the database with these defaults already in place .

这是一个good post on the Unicode gotchas in MySQL and their fixes .

在 Perl 方面,请务必使用 utf8,以便您传递到 MySQL 的字符串采用 utf8 编码。

最后根据DBD::mysql manual ,您需要在连接时而不是之后打开UTF8支持。如果能发出警告就好了。

Additionally, turning on this flag tells MySQL that incoming data should be
treated as UTF-8. This will only take effect if used as part of the call to
connect(). If you turn the flag on after connecting, you will need to issue
the command SET NAMES utf8 to get the same effect.

更改您的连接。

# I threw in RaiseError because its generally a good idea.
my $dbh = DBI->connect($dsn, $user, $pass, { mysql_enable_utf8 => 1, RaiseError => 1 });

关于mysql - 无法在 Perl 中使用 DBI 在 mysql 中插入变音符号文本的等效纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12836890/

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