使用JAVA中的会话用户进行MYSQL查询

时间:2016-06-16 14:15:57

标签: java mysql sql eclipse jdbc

我试图从Eclipse运行此查询:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession();
        String name = session.getAttribute("user").toString();
        String query = "SELECT DISTINCT t.text, t.user, t.date"
                + " FROM users u, tweets t, follows f" 
                + " Where t.parent is null"
                + " AND u.id ="+name
                + " AND ( f.follower = u.id"
                + " AND f.followed = t.user"
                + " OR t.user = u.id)"
                + " ORDER BY t.date DESC;";

但是我收到以下错误:

Sesion(user):Takeshi
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Takeshi' in 'where clause'

我可以想象这个错误是因为我在u.id和name之间的比较做错了,但是我应该怎么做呢?有一些特殊的性格?提前谢谢。

1 个答案:

答案 0 :(得分:-1)

请您使用以下代码段:

String name = session.getAttribute("user").toString();
name = name.replace("\'", "''"); 

String query =   " SELECT DISTINCT t.text, t.user, t.date"
                + " FROM users u, tweets t, follows f" 
                + " Where t.parent is null"
                + " AND u.id = '"+name+"'"
                + " AND ( f.follower = u.id"
                + " AND f.followed = t.user"
                + " OR t.user = u.id)"
                + " ORDER BY t.date DESC";