语法错误:遇到“;”

Posted

技术标签:

【中文标题】语法错误:遇到“;”【英文标题】:Syntax error: Encountered ";" 【发布时间】:2016-04-25 13:33:57 【问题描述】:

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

数据库类:

    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.

遇到什么“;”意思是,我能做些什么来纠正它?

【问题讨论】:

您希望我们读取 100 行来查找您的语法错误?!? 为什么不在执行之前打印出 sql 语句呢?将使调试更容易。 如果您使用的是 derby,为什么要标记 mysql 请改写public Boolean insertPlayer(User player)public void insertGameResult(Results result)使用PreparedStatementsetString() 【参考方案1】:

Encountered ";" 是什么意思,我能做些什么来纠正它?

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

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

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

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

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

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

【讨论】:

是的,我已经去掉了尾随;现在它向我展示了类似 java.sql.SQLIntegrityConstraintViolationException: Column 'GAME_NO' cannot accept a NULL value 的内容。 GAME_NO 是我的结果表中的列之一。 您可能想要更改您的表格以添加GAME_NO INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),以便数据库为您输入游戏编号。否则,您必须将游戏编号添加到 Results 类。 您已将GAME_NO 定义为NOT NULL,但显然您没有在该列中插入值(它未在您的INSERT 语句中列出)。修改表并删除 NOT NULL 约束或将该列添加到您的 INSERT 语句中。

以上是关于语法错误:遇到“;”的主要内容,如果未能解决你的问题,请参考以下文章

安装 PyOpenGLContext 时遇到问题(语法错误)

语法错误:遇到“ “第1栏第16栏

derby 语法错误:遇到 EOF Next Value 序列

在雪花中,在授予对存储过程的“使用”访问权限时,我遇到了语法错误

我在 mysql(js) 中遇到语法错误(错误:ER_PARSE_ERROR)

我在将我的 bash 命令转换为 shell 脚本中的 shell 脚本语法错误时遇到错误