【问题标题】:Foreign Key issue for creating a table using Java JDBC使用 Java JDBC 创建表的外键问题
【发布时间】:2021-02-01 03:50:50
【问题描述】:

代码在CreateTableExample() 中的PRIMARY KEY 行之前有效,但在其正下方,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();
            }
            }
}

【问题讨论】:

    标签: java sql eclipse ms-access jdbc


    【解决方案1】:

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

          String tablenm ="CREATE TABLE `" + str + "` "
                 + "(`" + str2 + "` VARCHAR(255), "       
                 + "PRIMARY KEY(`" + str2 + "`), "
                 + "FOREIGN KEY (`" + str2 + "`) " 
                 + "REFERENCES `" + otherTable + "` (`" + otherColumn + "`))";
    

    【讨论】:

    • 但 otherTable 不是必需的,引用:w3resource.com/sql/creating-and-maintaining-tables/…
    • @sean 该页面包括另一个表:REFERENCES [primary_key_table] (column_list_of_primary_key_table) ...);
    • 我说我在原始帖子中尝试了不同的表和列名,但仍然有同样的错误。
    • 请附上另一张表的CREATE TABLE ...
    猜你喜欢
    • 2011-05-06
    • 2014-11-19
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    相关资源
    最近更新 更多