java中如何在字符串中嵌入变量

来源:百度知道 编辑:UC知道 时间:2024/05/15 09:32:35
String str="张三"
比如说一个字符串sql语句“select * from student where name=”+str

我试过 这样不行 报错说 无效的列名
请问应该怎么表达这个语句的意思

用这个语句就可以:
"select * from student where name='" + str + "'"

因为"name"在你的数据库中被定义成了字符型,所以查询条件应该加上单引号,例如你要查名字叫“张三”的student,那么sql查询语句的格式就应该是:
"select * from student where name='张三'"

有什么问题吗
String str="张三";
String sql ="select * from student where name="+str;
System.out.println(sql);

这样是对的啊 或者你也可以

"select * from student where name= '"+str+"'"

楼主是不是做数据库的查询操作啊

这样的话也还是没错的啊 无效的列名 你的name字段对吗?是表中的字段吗

你应该把sql语句打印一下 看看是哪里除了问题

在Java中 + 号还可以表示连接符:
但前提是在输出语句里。即:
System.out.println();语句中;
如果是在一般的语句中肯定是要报错的。
因为在一般的赋值语句中系统会自动进行数据类型的转换。会把变量转换成String类型的。

无效的列名 ??
应该是name跟数据库列名对不上吧?
还有语句应该写成:"select * from student where name='"+str+"' "

select * from student where name='"+str+"'
//这个是一对单引号 里面一对双引号 然后拿一对双引