JAVA - SQL语法错误

时间:2015-04-24 18:25:46

标签: java mysql jdbc

我正在用Java创建一个方法。那是从数据库中检索消息,但我不断收到语法错误。有人能帮助我吗?

public static String retrieveMessages()
{
    PreparedStatement pstmt;
    try
    {
        pstmt = connection.prepareStatement("SELECT * from  tblEmail"
                + "INNERJOIN tblUser "
                +  "ON tblUser.username = tblEmail.`from`"
                +  "WHERE tblUser.username = ?");

        pstmt.setString(1, user.Getuser());
        results = pstmt.executeQuery();

    }
    catch (SQLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return (results.toString());

}

2 个答案:

答案 0 :(得分:2)

tblEmailinner之间以及fromwhere之间添加空格

pstmt = connection.prepareStatement("SELECT * from  tblEmail "
                                          + "INNER JOIN tblUser "
                                          +  "ON tblUser.username = tblEmail.`from` "
                                          +  "WHERE tblUser.username = ?");

答案 1 :(得分:1)

您需要添加空格(INNER之前和WHERE之前)。将查询拆分为多行并不会将一行的结尾与下一行的开头分开。

    pstmt = connection.prepareStatement("SELECT * from  tblEmail "
                                      + "INNER JOIN tblUser "
                                      +  "ON tblUser.username = tblEmail.`from` "
                                      +  "WHERE tblUser.username = ?");

当你写:

                                        "SELECT * from  tblEmail"
                                      + "INNER JOIN tblUser "

与以下内容相同:

                                        "SELECT * from  tblEmailINNER JOIN tblUser "