【问题标题】:How to save html file in MySQL DB using JDBC?如何使用 JDBC 将 html 文件保存在 MySQL DB 中?
【发布时间】:2012-12-31 22:12:07
【问题描述】:

我的 html 文件为 String,我想使用更新查询将其插入 MySQL DB。我试过这个:

Statement st = connection.createStatement();
String query = "UPDATE orders SET status='ready', html='"+html+"' WHERE id='123'";
int num = st.executeUpdate(query);

但我得到以下异常:

MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'zglosBladWindow').ck_window.showCenter('this');" href="#">zg?o? b??d na stronie<' at line 1

这是 HTML 中的某个地方 - 可能我不能只用 "" 引用 html 并插入它,因为它还包含许多特殊字符和引号 - 那么我该如何插入它呢?我应该以某种方式对其进行编码吗?

【问题讨论】:

  • 你必须转义变量html

标签: java mysql sql jdbc


【解决方案1】:

您应该使用PreparedStatement 构造,因为您的HTML 字符串可能包含引号或双引号。阅读更多here

【讨论】:

    【解决方案2】:

    我建议您使用 PreparedStatement 而不是 Statement。

    String query = "UPDATE orders SET status=?, html=? WHERE id=?";
    PreparedStatement stmnt = conn.PreparedStatement(query);
    stmnt.setString(1, yourtext);
    ....
    int num = st.executeUpdate();
    

    【讨论】:

    • 谢谢,这就是我一直在寻找的,但您的代码中几乎没有错误:应该是 int num = st.executeUpdate(query); 而不是 int num = st.executeUpdate();
    • @user606521 不客气,感谢您指出,这基本上是复制/粘贴的东西.. :)
    【解决方案3】:

    您应该使用 PreparedStatement,但我宁愿将路径保存在 MySQL 中,而不是保存文件。

    【讨论】:

      【解决方案4】:

      你可能应该使用这样的东西,

      StringBuilder contentBuilder = new StringBuilder();
      try {
      BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
      String str;
      while ((str = in.readLine()) != null) {
          contentBuilder.append(str);
      }
      in.close();
      } catch (IOException e) {
      }
      String content = contentBuilder.toString();
      

      【讨论】:

        猜你喜欢
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 2018-07-23
        相关资源
        最近更新 更多