mysql html,将HTML存储到MySQL数据库中

I'm trying to store a String which contains HTML in a MySQL database using Longtext data type. But it always says "You have an error in your SQL syntax". I tried to store a normal String and it works.

Update:

This is the query:

st.executeUpdate("insert into website(URL,phishing,source_code,active) values('" + URL + "','" + phishingState + "','" + sourceCode + "','" + webSiteState + "');");

I'm using Java.

解决方案

Strings in a SQL query are -usually- surrounded by singlequotes. E.g.

INSERT INTO tbl (html) VALUES ('html');

But if the HTML string itself contains a singlequote as well, it would break the SQL query:

INSERT INTO tbl (html) VALUES ('

');

You already see it in the syntax highlighter, the SQL value ends right before foo and the SQL interpreter can't understand what comes thereafter. SQL Syntax Error!

But that's not the only, it also puts the doors wide open for SQL injections (examples here).

You'll really need to sanitize the SQL during constructing the SQL query. How to do it depends on the programming language you're using to execute the SQL. If it is for example PHP, you'll need mysql_real_escape_string():

$sql = "INSERT INTO tbl (html) VALUES ('" . mysql_real_escape_string($html) . "')";

An alternative in PHP is using prepared statements, it will handle SQL escaping for you.

If you're using Java (JDBC), then you need PreparedStatement:

String sql = "INSERT INTO tbl (html) VALUES (?)";

preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, html);

Update: it turns out that you're actually using Java. You'll need to change the code as follows:

String sql = "INSERT INTO website (URL, phishing, source_code, active) VALUES (?, ?, ?, ?)";

preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, URL);

preparedStatement.setString(2, phishingState);

preparedStatement.setString(3, sourceCode);

preparedStatement.setString(4, webSiteState);

preparedStatement.executeUpdate();

Don't forget to handle JDBC resources properly. You may find this article useful to get some insights how to do basic JDBC stuff the proper way. Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值