如何在 SQL CHAR 中编码字符串
How to encode a string in a SQL CHAR
'admin'
编码为=CHAR(97, 100, 109, 105, 110)
我想知道是否有模块或方法可以将字符串的每个字母转换为 SQL CHAR
s。如果没有,我如何自己转换它?如果有帮助,我可以访问显示 a=97、b=98 等的图表。
我完全不确定您为什么需要这个。不难获得包含 ASCII 或 Unicode 或任何代码点的 CHAR
字段的字符串表示形式。但我很确定你不需要那个,因为数据库已经知道如何将它们与传入 SQL 等的字符串进行比较。除非你试图生成一个看起来与您从其他工具获得的那些。但是,假设您确实需要这样做,方法如下。
我认为您正在寻找 ord
函数:
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('\u2020') returns 8224. This is the inverse of chr().
这是有效的,因为 Python 可以访问您拥有的同一张图表——事实上,可以访问一堆不同的图表,一个对应它所知道的每种编码。事实上,该图表几乎就是编码 是 .
因此,例如:
def encode_as_char(s):
return 'CHAR({})'.format(', '.join(str(ord(c)) for c in s))
或者,如果您只想要一个数字列表,而不是由这些数字组成的字符串,则更简单:
def encode_as_char(s):
return [ord(c) for c in s]
这一切都假设 (a) 您的数据库正在存储 Unicode 字符并且您正在使用 Python 3,或者 (b) 您的数据库正在存储 8 位字符并且您正在使用 Python 2. 否则,您还需要 encode
或 decode
步骤。
对于一个Python 3 Unicode字符串到一个UTF-8数据库(注意我们这里不需要ord
,因为Python 3 bytes
是实际上是一个数字序列):
def encode_as_utf8_char(s):
return 'CHAR({})'.format(', '.join(str(c) for c in s.encode('utf-8')))
对于Python 2 UTF-8 字符串到 Unicode 数据库:
def encode_utf8_as_char(s):
return 'CHAR({})'.format(', '.join(str(ord(c)) for c in s.decode('utf-8')))
'admin'
编码为=CHAR(97, 100, 109, 105, 110)
我想知道是否有模块或方法可以将字符串的每个字母转换为 SQL CHAR
s。如果没有,我如何自己转换它?如果有帮助,我可以访问显示 a=97、b=98 等的图表。
我完全不确定您为什么需要这个。不难获得包含 ASCII 或 Unicode 或任何代码点的 CHAR
字段的字符串表示形式。但我很确定你不需要那个,因为数据库已经知道如何将它们与传入 SQL 等的字符串进行比较。除非你试图生成一个看起来与您从其他工具获得的那些。但是,假设您确实需要这样做,方法如下。
我认为您正在寻找 ord
函数:
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('\u2020') returns 8224. This is the inverse of chr().
这是有效的,因为 Python 可以访问您拥有的同一张图表——事实上,可以访问一堆不同的图表,一个对应它所知道的每种编码。事实上,该图表几乎就是编码 是 .
因此,例如:
def encode_as_char(s):
return 'CHAR({})'.format(', '.join(str(ord(c)) for c in s))
或者,如果您只想要一个数字列表,而不是由这些数字组成的字符串,则更简单:
def encode_as_char(s):
return [ord(c) for c in s]
这一切都假设 (a) 您的数据库正在存储 Unicode 字符并且您正在使用 Python 3,或者 (b) 您的数据库正在存储 8 位字符并且您正在使用 Python 2. 否则,您还需要 encode
或 decode
步骤。
对于一个Python 3 Unicode字符串到一个UTF-8数据库(注意我们这里不需要ord
,因为Python 3 bytes
是实际上是一个数字序列):
def encode_as_utf8_char(s):
return 'CHAR({})'.format(', '.join(str(c) for c in s.encode('utf-8')))
对于Python 2 UTF-8 字符串到 Unicode 数据库:
def encode_utf8_as_char(s):
return 'CHAR({})'.format(', '.join(str(ord(c)) for c in s.decode('utf-8')))