1

该代码一直运行到PRIMARY KEYin 行CreateTableExample(),但在该行的正下方,该FOREIGN KEY行一直给我一个错误,即使在周围使用不同的列名以及尝试将表名添加到该REFERENCES行时也是如此。即使没有必要,错误仍然存​​在。

这是错误:

java.sql.SQLSyntaxErrorException: unexpected token: (

这根本没有帮助,因为所有的括号都符合,使得错误所在的行无关紧要,因为它在第 20 行,包含: stmt.executeUpdate(tablenm);

我正在将 UcanAccess 与 Eclipse JDBC 一起用于 MS Access

完整的编译程序:

package test;
import java.sql.*;
import java.util.*;
public class test2 {
    
    static void CreateTableExample(Connection connection, Scanner sc) {
 
        System.out.print("Enter table name: ");  
        String str = sc.nextLine(); 
        System.out.print("Enter column name: ");  
        String str2 = sc.nextLine();

          String tablenm ="CREATE TABLE `" + str + "` "
                 + "(`" + str2 + "` VARCHAR(255), "       
                +  "PRIMARY KEY(`" + str2 + "`), "
                 + " FOREIGN KEY (`" + str2 + "`) REFERENCES(`" + str2 + "`))";
          try {
          Statement stmt = connection.createStatement();

          stmt.executeUpdate(tablenm);
          }
          
          catch (SQLException e) {
        e.printStackTrace();
    }
          
}


        public static void main(String[] args) {
             
            String databaseLoc = "jdbc:ucanaccess://C:\\Users\\14129\\Desktop\\test.accdb";
             
            try (Connection connection = DriverManager.getConnection(databaseLoc)) {
                
                Scanner sc= new Scanner(System.in); 
                CreateTableExample(connection, sc);
            }
                
            catch (SQLException ex) {
                ex.printStackTrace();
            }
            }
}
4

1 回答 1

0

外键通常引用另一个表(或同一个表)的另一列,而您缺少该部分。如果您将引用的表和列作为参数,例如 asotherTableotherColumn,您可以这样做:

      String tablenm ="CREATE TABLE `" + str + "` "
             + "(`" + str2 + "` VARCHAR(255), "       
             + "PRIMARY KEY(`" + str2 + "`), "
             + "FOREIGN KEY (`" + str2 + "`) " 
             + "REFERENCES `" + otherTable + "` (`" + otherColumn + "`))";
于 2020-10-18T03:21:32.183 回答