postgresql BPCHAR 数据类型与 VARCHAR 有何不同?

问题描述 投票:0回答:1
我试图理解postgresql中

bpchar

数据类型的用途,根据
官方文档,差异应该是它是空白修剪的,即使bp
中的
bpchar
代表空白填充已经让我感到困惑了。

我用 asyncpg 在 python 中尝试了一个简单的测试,其中我保存并读回一串空格,并且

varchar

bpchar
 都正确打印空格,表明它们已写入数据库并且没有发生修剪。我也尝试过用一个由几个空格包围的单词组成的字符串,结果是相同的。

这是带有

varchar

的代码:

import asyncpg import uvloop async def main(): print("varchar") # Establish a connection to an existing database named "test" # as a "postgres" user. conn = await asyncpg.connect('postgresql://postgres:postgres@localhost:5432/test') # Execute a statement to create a new table. await conn.execute(''' CREATE TABLE users( id serial PRIMARY KEY, name varchar ) ''') # Insert a record into the created table. await conn.execute(''' INSERT INTO users(name) VALUES($1) ''', ' ') # Select a row from the table. row = await conn.fetchrow( 'SELECT * FROM users') print(f"x{row.get("name")}x") # Close the connection. await conn.close() uvloop.run(main())
哪个输出:

varchar x x

bpchar

同样的事情:

import asyncpg import uvloop async def main(): print("bpchar") # Establish a connection to an existing database named "test" # as a "postgres" user. conn = await asyncpg.connect('postgresql://postgres:postgres@localhost:5432/test') # Execute a statement to create a new table. await conn.execute(''' CREATE TABLE users( id serial PRIMARY KEY, name bpchar ) ''') # Insert a record into the created table. await conn.execute(''' INSERT INTO users(name) VALUES($1) ''', ' ') # Select a row from the table. row = await conn.fetchrow( 'SELECT * FROM users') print(f"x{row.get("name")}x") # Close the connection. await conn.close() uvloop.run(main())
哪个输出:

bpchar x x
如您所见,

varchar

bpchar
都会产生相同的未修剪输出。
我做错了什么还是文档不清楚?

postgresql
1个回答
0
投票

bpchar

(或
character
)的目的是满足SQL标准。它没有任何实用价值,并且被认为是有害的(请参阅
文档中的“提示”)。 不要使用它。

如果您连接字符串或计算

varchar(n)

,您会注意到与 
length()
 的区别。

© www.soinside.com 2019 - 2024. All rights reserved.