JavaFX应用JDBC操作Derby数据库遇SQL词法错误的解决咨询
Hey there, let's break down your problem and fix it step by step! The java.sql.SQLSyntaxErrorException you're seeing is definitely caused by directly concatenating user input (like email addresses with @) into your SQL string. Here's what's happening and how to fix it:
Root Cause
When you build SQL queries by string concatenation (e.g., "INSERT INTO admins (email) VALUES ('" + userEmail + "')"), the database's SQL parser treats the @ in the email as part of SQL syntax instead of a regular character in a string. This triggers the lexical error you're seeing, because the parser doesn't expect an @ in that position outside of parameter placeholders or specific SQL clauses.
What Code to Modify
You'll need to replace your string-based query building with JDBC PreparedStatements—this is the standard, secure way to handle user input in SQL queries. Here's how to adjust your code:
1. Rewrite the AdminAccount.addAdmin Method
Instead of passing a concatenated SQL string to your Query class, use a parameterized query and set values via PreparedStatement:
// Inside AdminAccount.java (replace your current addAdmin method logic) public boolean addAdmin(String username, String email, String password) { String sql = "INSERT INTO admins (username, email, password) VALUES (?, ?, ?)"; try (Connection conn = DatabaseUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { // Set parameters (the ? placeholders are replaced safely) pstmt.setString(1, username); pstmt.setString(2, email); // @ symbol is automatically handled here pstmt.setString(3, password); int rowsInserted = pstmt.executeUpdate(); return rowsInserted > 0; } catch (SQLException e) { e.printStackTrace(); return false; } }
2. Update the Query.generateOperation Method (or Replace It)
If your Query class's generateOperation method is responsible for building raw SQL strings, you'll need to refactor it to support parameterized queries instead of string concatenation. For example:
// Inside Query.java (replace the old generateOperation logic) public PreparedStatement generateOperation(String sqlTemplate, Object... params) throws SQLException { Connection conn = getConnection(); // Your existing connection logic PreparedStatement pstmt = conn.prepareStatement(sqlTemplate); // Set each parameter in order for (int i = 0; i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } return pstmt; }
3. Adjust the UI Submit Event Handler
In your UI code where you trigger the admin addition, pass the raw input values directly to the updated addAdmin method (no need to escape or modify them):
// Example JavaFX submit button event handler submitButton.setOnAction(e -> { String username = usernameField.getText().trim(); String email = emailField.getText().trim(); String password = passwordField.getText().trim(); AdminAccount adminAccount = new AdminAccount(); boolean success = adminAccount.addAdmin(username, email, password); if (success) { // Show success message Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Success"); alert.setContentText("Admin added successfully!"); alert.showAndWait(); } else { // Show error message Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setContentText("Failed to add admin."); alert.showAndWait(); } });
Why This Works
- PreparedStatements automatically escape special characters: The JDBC driver handles characters like
@, single quotes ('), and newlines, ensuring they're treated as part of the input string instead of SQL syntax. - Prevents SQL injection: This is a critical security benefit—string concatenation leaves your app vulnerable to malicious input that can alter or destroy your database.
- Cleaner, more maintainable code: Parameterized queries are easier to read and modify than messy string concatenation.
Final Note
Never build SQL queries by concatenating user input again—PreparedStatements are the industry standard for this exact scenario. This fix will not only resolve your current @ symbol error but also make your database interactions more secure and robust.
内容的提问来源于stack exchange,提问作者Alex Bakic

