遵循本教程http://www.sqlite.org/foreignkeys.html我需要一个包含3个表的数据库,但是我无法修复有关“SQL逻辑错误......在国外附近”的消息
Private Sub CreateDataBase()
Dim conn = New SQLiteConnection("Data Source=MyDataBase.sqlite;Version=3")
Try
Using (conn)
conn.Open()
'3 Tables I need to create
Dim mainTable = "CREATE TABLE IF NOT EXISTS users (userID INTEGER PRIMARY KEY, name VARCHAR(20))"
Dim tableA = "CREATE TABLE IF NOT EXISTS tableA (ItemA VARCHAR(20), user INTEGER) FOREIGN KEY(user) REFERENCES users (userID)"
Dim tableB = "CREATE TABLE IF NOT EXISTS tableB (ItemB VARCHAR(20), user INTEGER) FOREIGN KEY(user) REFERENCES users (userID)"
Dim cmdConexion As SQLiteCommand = New SQLiteCommand(mainTable, conn)
'Try for the mainTable
Try
cmdConexion.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'Set and Try for tableA
cmdConexion.CommandText = tableA
Try
cmdConexion.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'Set and Try for tableB
cmdConexion.CommandText = tableB
Try
cmdConexion.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
相同的代码仅适用于mainTable。
我试过像
这样的一行Pragma("foreign_keys") = 1
甚至
cmdConexion.CommandText = "PRAGMA foreign_keys = ON"
但我仍无法解决错误。
SQL行或Pragma上的错误在哪里?
注意: 另外,是否有另一种方法可以在同一个Try-Catch上执行SQL Create Table,或者更好的方法是为每个表执行一次Try-Catch?
答案 0 :(得分:2)
CREATE TABLE语句中存在语法错误。 FOREIGN KEY - 部分必须在括号内
CREATE TABLE IF NOT EXISTS tableA (
ItemA VARCHAR(20),
user INTEGER,
FOREIGN KEY(user) REFERENCES users (userID)
)
或只是
CREATE TABLE IF NOT EXISTS tableA (
ItemA VARCHAR(20),
user INTEGER REFERENCES users (userID)
)
注意:错误的是" ...附近的东西"通常只是语法错误。