更新文本字段时在 postgresql 中插入换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26638615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 05:48:33  来源:igfitidea点击:

Insert line break in postgresql when updating text field

postgresqlcharsql-update

提问by alexyes

I am trying to update a text field in a table of my postgresql database.

我正在尝试更新我的 postgresql 数据库表中的文本字段。

UPDATE public.table SET long_text = 'First Line' + CHAR(10) + 'Second line.' WHERE id = 19;

My intended result is that the cell will look like this:

我的预期结果是该单元格将如下所示:

First Line
Second line

The above syntax returns an error.

上述语法返回错误。

回答by Mike Sherrill 'Cat Recall'

You want chr(10)instead of char(10).

你想要chr(10)而不是char(10).

Be careful with this, because that might be the wrong newline. The "right" newline depends on the client that consumes it. Macs, Windows, and Linux all use different newlines. A browser will expect <br />.

小心这一点,因为那可能是错误的换行符。“正确”的换行符取决于使用它的客户端。Mac、Windows 和 Linux 都使用不同的换行符。浏览器将期望<br />.

It might be safest to write your update like this for PostgreSQL 9.1+. But read the docs linked below.

为 PostgreSQL 9.1+ 编写这样的更新可能是最安全的。但请阅读下面链接的文档。

UPDATE public.table 
SET long_text = E'First Line\nSecond line.' 
WHERE id = 19;

The default value of 'standard_conforming_strings' is 'on' in 9.1+.

在 9.1+ 中,' standard_conforming_strings'的默认值为'on'。

show standard_conforming_strings;

回答by Craig Ringer

Use a literal newline (if standard_conforming_strings = on, i.e. you're on a recent PostgreSQL):

使用文字换行符(如果standard_conforming_strings = on,即您使用的是最近的 PostgreSQL):

UPDATE public.table 
SET long_text = 'First Line
Second line.' 
WHERE id = 19;

or you can use an escape:

或者您可以使用转义符:

UPDATE public.table 
SET long_text = E'First Line\nSecond line.'
WHERE id = 19;

回答by Maryam Homayouni

In my version of postgres, \n didnt work for line break and i used \r\n instead, like this:

在我的 postgres 版本中,\n 不适用于换行符,我使用 \r\n 代替,如下所示:

UPDATE public.table 
SET long_text = E'First Liner\r\nSecond line.'
WHERE id = 19;