servlet中如何写sql语句?
代码是这样的:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException,
IOException {
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
response.setCharacterEncoding("GBK");
String username = (String)request.getSession().getAttribute("user");
String unitname = request.getParameter("units");
String sql1="select * from student_sch where uname="+username+" and unitname="+unitname+" order by unitname asc,snumber asc";
String sql2="select * from student_org where uname="+username+" and unitname="+unitname+" order by unitname asc,identityId asc";
ResultSet rs = null;
try {
openDB();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
if(isSchool(request, response)){
rs = stmt.executeQuery(sql1);
}else{
rs = stmt.executeQuery(sql2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs!=null && !rs.next()){
request.setAttribute("unitStuString", "empty");
}else{
request.setAttribute("unitStuResultSet", rs);
}
} catch (
SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("main/chargeManage/stuList_View.jsp").forward(request, response);
}
字符编码没问题,也不管username和unitname是不是取到值了,只是那两个sql语句写的不对,是不是不能用+连接?这种情况下的sql语句应该怎么写啊?
我用的是mysql5.5
错误提示是com.mysql.jdbc.exceptions.jdbc4.MY
SQLSyntaxErrorException: Unknown column '一堆乱码打不出来' in 'where clause'。
拜谢了!!
------解决方案--------------------
String sql1="select * from student_sch where uname="+username+" and unitname="+unitname+" order by unitname asc,snumber asc";
==》
String sql1="select * from student_sch where uname='"+username+"' and unitname='"+unitname+"' order by unitname asc,snumber asc";
sql2也类似