您的位置:首页 > 数据库

向数据库中插入含有单引号的字符串

2016-10-11 20:58 302 查看
在项目中很容易遇到需要向数据库中插入含有单引号的字符串,但是字符串的单引号又会作为字符串的截止符号从而使得sql语句产生错误。因此需要对字符串进行相应处理之后才可以继续操作。

在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息