【问题标题】:String value Error in mysql with utf8 encoding使用utf8编码的mysql中的字符串值错误
【发布时间】:2015-03-01 12:50:45
【问题描述】:

我正在使用带有 ScalikeJDBC 的 scala,我的表编码是带有 utf8mb4_general_ci 集合的 utf8mb4,我得到:

03/01/2015 08:40:57 - ERROR[http-apr-8080-exec-9] StatementExecutor$$anon$1 - SQL execution failed (Reason: Incorrect string value: '\xF0\x9F\x98\x8A' for column 'body' at row 81):

即使我的数据源代码是:

val dataSource: DataSource = {
    val ds = new HikariDataSource()
    ds.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    ds.addDataSourceProperty("url", "jdbc:mysql://" + org.Server.GlobalSettings.DB.mySQLIP + ":3306?rewriteBatchedStatements=true")
    ds.addDataSourceProperty("user", "SOMEUSER")
    ds.addDataSourceProperty("password", "SomePassword")
    ds.setAutoCommit(false) // dosne't work

    ds.addDataSourceProperty("cachePrepStmts", "true")
    ds.addDataSourceProperty("prepStmtCacheSize", "250")
    ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
    ds.addDataSourceProperty("useServerPrepStmts", "true")
    ds.addDataSourceProperty("useUnicode", "yes")
    ds.addDataSourceProperty("characterEncoding", "utf8")
    ds.addDataSourceProperty("connectionCollation", "utf8_unicode_ci")

    //      ds.addDataSourceProperty("characterEncoding", "utf8mb4") //dosne't work either
    //      ds.addDataSourceProperty("connectionCollation", "utf8mb4_unicode_ci")//dosne't work either
    ds
  }

对于正文栏,我这样做:

 try{
    .
    .
    .
        body = new String(rev.body.getBytes("utf-8"), "utf-8") 
    .
    .
    .
    }

没有发现异常,但仍然在查询提交时失败:''字符串值不正确:...对于列'body''',一次又一次,有人可以帮助我吗?

【问题讨论】:

    标签: mysql scala jdbc encoding hikaricp


    【解决方案1】:

    让你编码为 UTF-8:

    body = new String(rev.body.getBytes("utf-8"), "UTF-8")
    

    或使用java.nio.charset.StandardCharsets.UTF_8。

    【讨论】:

    • 这样做毫无意义。您有一个 Java 字符串,获取特定编码的字节,然后使用相同的编码从这些字节创建一个新字符串。最终结果是相同的字符串值。
    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 2011-12-01
    • 1970-01-01
    • 2012-08-20
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多