拼接规则示例

java中的字符串只能双引号,如果字符串中需要拼接变量,该变量用单引号括起来,然后加两个双引号再加两个加号,中间就是变量。

例如:查询数据库中的用户名和密码。

注:为和sql表中的username和password字段相区别,我们在java中定义String变量分别为user_name和pass_word

// 正确结果
String sql = "select * from user where username = '"+user_name+"'and password = '"+pass_word+"'";

拼接步骤

  1. 写出SQL具体语句(无变量都是具体值的),比如上面的sql。
String sql = "select * from user where username = root and password = 123";

2.此时要将root和123分别用一对单引号代替

String sql = "select * from user where username = '' and password = ''";

3.接着在单引号中间分别加上一对双引号" "

String sql = "select * from user where username = '""' and password = '""'";

4.接着在分别在双引号中间加上一对加号+ +

String sql = "select * from user where username = '"++"' and password = '"++"'";

5.最后就是加号中间加上变量idd完事

String sql = "select * from user where username = '"+user_name+"' and password = '"+pass_word+"'";

口诀:先SQL原型,替换为单引,中间加双引,中间加双加号,中间加变量。