在JDBC中使用MySql转义单引号 [英] Escaping single quotes in JDBC with MySql

查看:444
本文介绍了在JDBC中使用MySql转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了代码,将来自新闻网站的一些标题存储在数据库中。然而,标题也时常包含(')单引号和双引号,并且当尝试将其插入表中时会导致错误。

I have written code to store some headline's from news websites in a database. However the headlines also contain (') single quotes and double quotes from time to time and this causes an error when trying to insert it into the table.

这是最好的方式。

这是我的代码:

Statement st = con.createStatement();
int val = st.executeUpdate("INSERT into imageinfo(imageurl,title,headline,website) VALUES('"+imageurl+"','"+title+"','"+headline+"','"+website+"')");


推荐答案

您应该考虑使用准备的语句,其中SQL查询是预编译的。根据您的数据来自哪里,这可能也防止SQL注入。

You should consider using Prepared Statements where your SQL queries are precompiled. Depending on where your data is coming from in the first place this may also guard against SQL Injections.

使用预准备语句的另一个优点是,您可以重复使用相同的语句每次执行时都有不同的参数。

Another advantage of using prepared statements is that you can reuse the same statement with different parameters each time you execute it.

这篇关于在JDBC中使用MySql转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆