VB.NET使用SQL在Access中的现有表中创建FOREIGN KEY?

时间:2015-10-01 09:23:14

标签: sql vb.net ms-access

我在VB.NET中以编程方式创建关系时遇到了一些课程问题。我不断收到&#34的错误;关系必须在具有相同数据类型的相同数量的字段上。"尽管事实上它是一个NUMBER的AUTOINCREMENT。 这是我正在使用的代码,请记住它创建表就好了。任何帮助将不胜感激。

CODE:

    Dim con As OleDbConnection

    Dim command As OleDbCommand

    Dim cat As New Catalog
    If My.Computer.FileSystem.FileExists("C:\Users.......\TEST.accdb") = False Then
        Dim str(3) As String
        cat.Create("Provider=microsoft.jet.oledb.4.0;Data Source = C:\Users........\TEST.accdb;jet oledb:engine type=5")
        cat = Nothing
        con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source =C:\Users.......TEST.accdb")
        con.Open()
        str(0) = "CREATE TABLE [tbl_Student] ([StudentID] AUTOINCREMENT NOT NULL PRIMARY KEY, [CourseID] NUMBER)"
        str(1) = "CREATE TABLE [tbl_Course] ([CourseID] AUTOINCREMENT NOT NULL PRIMARY KEY)"
        For i = 0 To 1
            command = New OleDbCommand(str(i), con)
            command.ExecuteNonQuery()
        Next
        con.Close()

        con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source =C:\Users........TEST.accdb")
        con.Open()
        Try
            str(3) = "ALTER TABLE [tbl_Student] ADD FOREIGN KEY (CourseID) REFERENCES tbl_Course(CourseID)"
            command = New OleDbCommand(str(3), con)
            command.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ErrorToString)
        End Try
        con.Close()
    End If

1 个答案:

答案 0 :(得分:1)

NUMBER不是Access中CREATE TABLE的已定义数据类型。我很惊讶它的工作原理。

改为使用LONG

请参阅Microsoft Access Data Types(列"数据类型(CREATETABLE)")