免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1971 | 回复: 1
打印 上一主题 下一主题

用 MySQL 函数转换字符集交流 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-04-16 11:54 |只看该作者 |倒序浏览
问题描述

存储过程中有 2 个变量:
  1.   declare code_gb2312 int unsigned default 0;
  2.   declare code_utf8 int unsigned default 0;
复制代码
我先已知 code_gb2312 的值,比如以 '中' 字(gb2312 码为 0xd6d0)为例:
set code_gb2312 = 0xd6d0;

怎样把它的 utf8 码得到,放到 code_utf8 中。

我的几个做法

首先定义几个字符变量:
  1. declare hanzi_gb2312 char(4) default '';
  2. declare hanzi_utf8 char(4) default '';
  3. declare str_tmp char(255) default '';
复制代码
把 code_gb2312 做成 gb2312 字符放到 hanzi_gb2312 中,再转字符集 utf8 到 hanzi_utf8:
  1. set hanzi_gb2312 = char(code_gb2312 using gb2312);
  2. set hanzi_utf8 = convert(hanzi_gb2312 using utf8);
复制代码
做法 1:
  1. set str_tmp = hex(hanzi_utf8);
  2. set code_utf8 = cast(conv(str_tmp, 16, 10) as unsigned);
复制代码
做法 2:
  1. set str_tmp = hex(hanzi_utf8);
  2. set code_utf8 = conv(str_tmp, 16, 10);
复制代码
这个就是方法 1,只是我发现 cast() 不必要。

做法 3:
  1. set code_utf8 = ord(hanzi_utf8);
复制代码
交流

有没有更好的方法呢?要求是,不要 warning(或给出忽略告警的方法),函数调用尽量少。

最好不要用 ord(),它只能抽第一个字符的编码,后面的怎么办?

另外,我觉得 ord() 这个家伙是根据被转字符类型的字符集来的,要不它怎么知道多少个非 ASCII 字符字节该拼成一个多字节字符,对么?那么请问字符类型变量在定义时,是否能指定字符集呢,就跟列类型一样。

论坛徽章:
0
2 [报告]
发表于 2010-04-16 11:57 |只看该作者
手册上 ord() 的说明太少了:

ORD(str)

If the leftmost character of the string str is a multi-byte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula:

  (1st byte code)
+ (2nd byte code × 256)
+ (3rd byte code × 2562) ...

If the leftmost character is not a multi-byte character, ORD() returns the same value as the ASCII() function.

mysql> SELECT ORD('2');
        -> 50
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP