向数据库中插入含有单引号的字符串
2016-10-11 20:58
302 查看
在项目中很容易遇到需要向数据库中插入含有单引号的字符串,但是字符串的单引号又会作为字符串的截止符号从而使得sql语句产生错误。因此需要对字符串进行相应处理之后才可以继续操作。
在java中可能会出现如下异常:
此时将字符串中的单引号" ' "替换成" ' ' "两个单引号即可。
此时应该利用java中的“replace”方法进行替换。此处给出java中的替换代码。
此时的输出结果:
因java要对数据库进行操作需要引入相应的驱动所以分享连接Mysql驱动
下载地址:http://download.csdn.net/download/ldutyk/9684893
在java中可能会出现如下异常:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.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 'm a boy')' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.Util.getInstance(Util.java:386) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2713) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1794) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1712) at test.Server.operate(Server.java:51) at test.test.main(test.java:10)
此时将字符串中的单引号" ' "替换成" ' ' "两个单引号即可。
此时应该利用java中的“replace”方法进行替换。此处给出java中的替换代码。
public static void main(String[] args) throws Exception{ Server ss=new Server(); String str="I'm a boy"; String temp=str.replaceAll("'", "''"); String sql="insert into test VALUES('"+temp+"');"; ss.operate(sql, 2); System.out.println(temp); System.out.println(sql); }
此时的输出结果:
I''m a boy insert into test VALUES('I''m a boy');此时可以正确针对数据库进行操作。
因java要对数据库进行操作需要引入相应的驱动所以分享连接Mysql驱动
下载地址:http://download.csdn.net/download/ldutyk/9684893
相关文章推荐
- 插入和更新数据库时字符串中含有转义字符的处理方法
- [急]Oracle Clob字段插入数据库时报:字符串长度过长
- 解决字符串插入不能大于2000.(用的数据库环境为Oracle 9i; 10g不能大于4000)
- 如何在oracle中插入含有半角单引号'的字符串
- 向数据库插入带有单引号(')的字符串
- 如何向数据库插入带有单引号(')的字符串?
- 搜索当前数据库中含有指定字符串的表列
- 关于Mysql查询带单引号及插入带单引号字符串问题
- 如何向数据库插入带有单引号(')的字符串?--在做数据插入是一定要考虑,否则有单引号系统就会报错
- 数据库中插入字符串
- 在oracle数据库中插入含有&符号的字符串
- [Tip]如何在SQL*PLUS中插入含有&的字符串?
- 在SQL*PLUS中插入含有&的字符串
- 在SQL*PLUS中插入含有&的字符串
- android sqlite中字符串含有单引号的处理
- C#随机获得字符串组成帐号和密码并插入到数据库,将插入成功的数据计入文本
- 如何向数据库中插入包含单引号的记录
- 数据库中查询的字段中含有单引号的处理方式
- c#截取字符串函数 以及将每段字符串插入到数据库
- 向数据库中添加含有单引号的数据