【问题标题】:SQL UPDATE statement with large HTML data包含大量 HTML 数据的 SQL UPDATE 语句
【发布时间】:2020-08-11 04:51:30
【问题描述】:

我有一些自动化的工作流程,其中包括通过 SQL 更新包含 HTML 标记的列。

基本的 SQL 语句如下:

UPDATE content SET bodytext = '<div class="one two three">Here comes a whole lot of HTML with all special chars and double quotes " and single quotes ' and empty lines and all possible kind of stuff...</div>' WHERE pid = 10;

有没有办法让 MariaDB 或 MySQL 在 SQL(不使用 PHP)中自动转义?

【问题讨论】:

  • 编写一个返回转义文本的函数。
  • @nicomp 谢谢你的想法。请您详细说明一个最小的示例吗?
  • 类似 SELECT REPLACE ('a"bc', '"', '\'"\'')

标签: sql replace escaping


【解决方案1】:

我建议使用准备好的语句。这样您就可以将语句与其参数分开,并且不需要关心普通 SQL 中所需的额外转义。

使用 PHP 的 MySQLi 驱动程序中提供的功能可以简化流程:

https://www.w3schools.com/php/php_mysql_prepared_statements.asp

在普通 SQL 中也可以使用准备好的语句,但我不确定手动执行是否值得麻烦

https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html

【讨论】:

    【解决方案2】:

    感谢您的意见,但我认为,我找到了适合我的解决方案。看来您实际上可以通过这种语法告诉 SQL 服务器接受原始字符串:

    SELECT q'[The 'end' of the day]'

    (来源:https://www.databasestar.com/sql-escape-single-quote/

    所以我做了以下事情:

    SELECT @html := '[<div class="one two three">Here comes a whole lot of HTML with all special chars and double quotes " and single quotes '' and empty lines and all possible kind of stuff...</div>]';
    UPDATE content SET bodytext = @html WHERE pid = 10;
    

    而且它以这种方式工作,没有任何逃避问题。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 2011-02-13
      • 2021-12-21
      • 1970-01-01
      • 2019-12-03
      • 2023-02-01
      • 2017-04-23
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多