【问题标题】:How to sanitize strings for storage in a sqlite database?如何清理字符串以存储在 sqlite 数据库中?
【发布时间】:2012-07-22 08:30:29
【问题描述】:

我正在尝试将 mp3 中的标签存储在 sqlite 数据库中,但出现以下错误:

 
SQL (0.3ms)  INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["album", "\xFF\xFE2\x001\x00"], ["artist", "\xFF\xFEa\x00d\x00e\x00l\x00e\x00"], ["created_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00], ["length", 15], ["path", "/audios/music/Adele - Discography (Complete) [2008 - 2011]/Adele - 21 [2011] + Bonus Tracks/01. Adele - Rolling in the Deep.mp3"], ["store_id", 3], ["title", "\xFF\xFEr\x00o\x00l\x00l\x00i\x00n\x00g\x00 \x00i\x00n\x00 \x00t\x00h\x00e\x00 \x00d\x00e\x00e\x00p\x00"], ["track_number", "01"], ["updated_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00]]
Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
   (0.2ms)  rollback transaction
ActiveRecord::StatementInvalid: Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
 

我怎样才能剥离或净化输入?

【问题讨论】:

  • 输入数据真的看起来像'\xFF\xFE2\x001\x00'吗?
  • 数据是从 id3 标签自动生成的,大多数程序似乎去掉了这些字符,其他程序将它们显示为空框或问号。我使用Song.new并分别设置每个值,错误代码将垃圾字符显示为问号,但更改为Song.create( hash )后显示上面的内容。
  • Axctivrecord 抱怨Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8,但很明显\xFF\xFE2\x001\x00 不在ASCII-8BIT 编码中。因此,您可以通过在调用 ActiveRecord 之前将 id3 标签转换为 UTF-8 来解决此问题。
  • @denis.peplin 你介意给出如何做到这一点的示例代码吗,string::encode 的语法有点混乱
  • "源字符串".encoding(dst_encoding, src_encoding)。 ruby-doc.org/core-1.9.3/String.html#method-i-encode

标签: ruby-on-rails sqlite sanitization


【解决方案1】:

ActiveRecord 抱怨Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8,但很明显\xFF\xFE2\x001\x00 不在ASCII-8BIT 编码中。因此,您可以通过在调用 ActiveRecord 之前将 id3 标签转换为 UTF-8 来解决此问题。

"source string".encoding(dst_encoding, src_encoding).

文档:http://www.ruby-doc.org/core-1.9.3/String.html#method-i-encode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多