语法错误:遇到“;”

时间:2016-04-25 13:33:57

标签: java sql jdbc derby

我正在尝试将我的tic tac toe游戏结果输出到数据库。但是,只要两个客户端之间的匹配完成,我就会遇到此错误。这是我的服务器端代码的摘录和错误消息:

数据库类:

    import java.sql.*;
    import java.util.*;
    import javax.swing.JOptionPane;

    class Database {

final String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDriver";
final String DB_URL = "jdbc:derby://localhost:1527/Mini Project";

//  Database credentials
final String USER = "Joe";
final String PASS = "plateau";

Connection conn; 
Statement stmt;

public Database() {

    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");

        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = (Statement) conn.createStatement();

    } catch (SQLException ex) {
        ex.printStackTrace();

    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();

    }

}

public User getUser(String userName) {

    User user = null;

    try {
        ResultSet resultSet = stmt.executeQuery("SELECT * FROM PLAYERS");

        while (resultSet.next()) {
            //Retrieve by column name
            user = new User(resultSet.getInt(1),
                    resultSet.getString(2),
                    resultSet.getString(3),
                    resultSet.getString(4),
                    resultSet.getString(5),
                    resultSet.getString(6)); 
        }

        resultSet.close(); 

    } catch (SQLException ex) {
        ex.printStackTrace();
        System.err.println(ex.toString());
    }

    return user;

}

public Boolean insertPlayer(User player) {

    Boolean isAdded = false;

    int DUPLICATE_PRIMERY_KEY_ERROR_CODE = 1062;

    String sql = "INSERT INTO PLAYERS(Name,Surname,Username,Password,Email) VALUES('" 
            + player.getName() + "','" + player.getSurname() + "','" + player.getUsername() + "','"
            + player.getPassword() + "','" + player.getEmail() + "','" 
            + "','" + "');";

    try {
        stmt.execute(sql);
        isAdded = true;

    } catch (SQLException ex) {

        isAdded = false;
        ex.printStackTrace();
        System.err.println(ex.toString());

        if (ex.getErrorCode() == DUPLICATE_PRIMERY_KEY_ERROR_CODE) {
            JOptionPane.showMessageDialog(null, "Username with or email already exist");
        }

    }

    return isAdded;
}

public void insertGameResult(Results result) {

    String igr = "INSERT INTO RESULTS(Name1, Surname1, Name2, Surname2, Winner) VALUES('" 
            + result.getName1() + "','" + result.getSurname1() + "','" + result.getName2() + "','" 
            + result.getSurname2() + "','" + result.getWinner() + "');";

    try {
        Boolean added = stmt.execute(igr);                                                   
        if (added) {
            JOptionPane.showMessageDialog(null, "Result added successfuly");
        }
    } catch (SQLException ex) {

        ex.printStackTrace();
        System.err.println(ex.toString());

    }

}
    }

玩家类:

    class Player extends Thread {

    Socket insocket;
    Socket outSocket;

    public Player(Socket sock, Socket opnSock) {
        this.insocket = sock;
        this.outSocket = opnSock;

    }

    @Override
    public void run() {

        try {

            while (true) {

                InputStream is = insocket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                String readData = br.readLine();

                OutputStream os = outSocket.getOutputStream();
                PrintWriter pw = new PrintWriter(os, true);
                pw.println(readData);
                // logTextArea.append(Rdata + "\n");

                if (readData.contains("winner*")) {

                    String[] splitData = readData.split(",");
                    String player1 = splitData[1];
                    String player2 = splitData[2];
                    int winner = Integer.valueOf(splitData[3]);

                    win += 1;
                    if (win == 2) {
                        saveResult(player1, player2, winner);

                        if (winner == 1) {
                            winner = 2;
                        } else if (winner == 2) {
                            winner = 1;
                        }

                        saveResult(player2, player1, winner);
                        win = 0;
                    }

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            jtaLog.append(ex.toString() + "\n");
        }
    }
}

主类下的保存结果方法:

    public void saveResult(String username1, String username2, int winner) {

    User p1 = database.getUser(username1);
    User p2 = database.getUser(username2);

    Results result = new Results(0, p1.getName(), p1.getSurname(), p2.getName(), p2.getSurname(), winner);
    database.insertGameResult(result); 
    }

以下是我收到的错误消息:

java.sql.SQLSyntaxErrorException: Syntax error: Encountered ";" at line 1, column 98.
    at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
    at org.apache.derby.client.am.ClientStatement.execute(Unknown Source)
    at tictactoeserver.Database.insertGameResult(Database.java:106)
    at tictactoeserver.TicTacToeServer.saveResult(TicTacToeServer.java:200)
    at tictactoeserver.TicTacToeServer$Player.run(TicTacToeServer.java:317)
Caused by: ERROR 42X01: Syntax error: Encountered ";" at line 1, column 98.
    at org.apache.derby.client.am.ClientStatement.completeSqlca(Unknown Source)
    at org.apache.derby.client.am.ClientStatement.completeExecuteImmediate(Unknown Source)
    at org.apache.derby.client.net.NetStatementReply.parseEXCSQLIMMreply(Unknown Source)
    at org.apache.derby.client.net.NetStatementReply.readExecuteImmediate(Unknown Source)
    at org.apache.derby.client.net.StatementReply.readExecuteImmediate(Unknown Source)
    at org.apache.derby.client.net.NetStatement.readExecuteImmediate_(Unknown Source)
    at org.apache.derby.client.am.ClientStatement.readExecuteImmediate(Unknown Source)
    at org.apache.derby.client.am.ClientStatement.flowExecute(Unknown Source)
    at org.apache.derby.client.am.ClientStatement.executeX(Unknown Source)
    ... 4 more
java.sql.SQLSyntaxErrorException: Syntax error: Encountered ";" at line 1, column 98.

遇到了什么“;”是什么意思,我该怎么做才能纠正它?

1 个答案:

答案 0 :(得分:8)

  

Encountered ";"是什么意思,我该怎么做才能纠正它?

这意味着您的SQL语句有一个额外的;字符,而SQL解析器并不期望这个字符。虽然通常在交互式SQL shell中使用;终止SQL命令,但在通过JDBC执行SQL命令时,不得添加它们。

在您的情况下,在INSERT语句中,删除尾随;,例如insertPlayer()方法:

...
+ "','" + "');";
             ^

您的insertGameResult()方法也是如此(这是堆栈跟踪实际显示的方法):

...  
+ result.getSurname2() + "','" + result.getWinner() + "');";
                                                         ^

另外,作为附加说明,在构建SQL语句时不要使用字符串连接。这使得语句易受SQL injections的攻击。改为使用绑定变量。