SQL命令未正确结束

时间:2016-05-24 05:58:19

标签: oracle

我尝试在java中创建一个从sql访问某些表的代码但是当我尝试运行代码时出现错误说:

  

java.sql.SQLSyntaxErrorException:ORA-00933:SQL命令不正确   结束

以下是它给我带来麻烦的代码:

history.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent actionEvent)
    {
        for(int i = 0; i < table.getRowCount(); i++)
            for(int j = 0; j < table.getColumnCount(); j++)
                table.setValueAt("", i, j);

        int i=0;
        try
        {
            rs = stmt.executeQuery("SELECT toyname, toyid, price "
                    +" FROM toys t, userbuy u " 
                                                +" WHERE u.toyid=t.toyid "
                    +" AND u.userid= "+user1.getUserid()+" )");
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if(rs.next())
                {
                    table.setValueAt(rs.getString(1), i, 0);
                    table.setValueAt(rs.getString(2), i, 1);
                    table.setValueAt(rs.getString(3), i, 2);
                    i++;
                    while(rs.next())
                    {
                        table.setValueAt(rs.getString(1), i, 0);
                        table.setValueAt(rs.getString(2), i, 1);
                        table.setValueAt(rs.getString(3), i, 2);
                        i++;
                    }
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
            }
        }
    }
});

这是我的两张桌子:

CREATE TABLE users
(
  userid    NUMBER(2) NOT NULL CONSTRAINT users_pk PRIMARY KEY,
  username        VARCHAR(17) NOT NULL,
  password    VARCHAR(20),
  email   VARCHAR(20),
  adress    VARCHAR(20),
  CNP     VARCHAR(14)
);
CREATE TABLE userbuy
(
  userid    NUMBER(2),
  buyid    NUMBER(2) ,
  toyid NUMBER(2),
  CONSTRAINT userid_fk FOREIGN KEY (userid) REFERENCES users(userid),
  CONSTRAINT buyid_fk FOREIGN KEY (buyid) REFERENCES buy(buyid)
);

有谁知道这里有什么问题?

3 个答案:

答案 0 :(得分:2)

你的sql查询是错误的。正确的sql

rs = stmt.executeQuery("SELECT toyname, toyid, price "
                            +" FROM toys t, userbuy u "                                                     +" WHERE u.toyid=t.toyid "
                            +" AND u.userid= "+user1.getUserid());

建议您使用PreparedStatement删除sql injection

PreparedStatement

的示例

答案 1 :(得分:1)

正确的sql查询:

rs = stmt.executeQuery("SELECT t.toyname, t.toyid, t.price "
                  +" FROM toys t, userbuy u "+" WHERE u.toyid=t.toyid "
                   +" AND u.userid= "+user1.getUserid());

答案 2 :(得分:1)

删除" )",可能是您忘了它:)