简体   繁体   English

具有SQLite和外键的C#

[英]C# with SQLite and foreign key

I want to implement a patients data base for our software, and have an issue with the foreign key statement. 我想为我们的软件实现一个患者数据库,并且外键声明有问题。 I am using the latest SQLite DLLs, with C#. 我正在使用带有C#的最新SQLite DLL。

When I try to run below code: 当我尝试运行以下代码时:

dbConnection = "Data Source=SQLiteMyDatabase.db;foreign keys=true;";
if (connections == 0)
{
  cnn = new SQLiteConnection(dbConnection);
  cnn.Open();
  this.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS patients ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) NOT NULL;");
  this.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS images ( FOREIGN KEY (patientID) REFERENCES patients(id), nameRed VARCHAR(20) NOT NULL PRIMARY KEY;");
}

I get the error: 我收到错误:

SQLite error near "FOREIGN": syntax error

Why does this happen? 为什么会这样?

In order to create a foreign key, you must first create the column: 为了创建外键,必须首先创建列:

CREATE TABLE IF NOT EXISTS images (
    nameRed VARCHAR(20) NOT NULL PRIMARY KEY, 
    patientID INT, 
    FOREIGN KEY (patientID) REFERENCES patients(id) 
 );

Please note: 请注意:

  1. I moved the primary key column ( nameRed ) first in the list of columns created, but that's just convention. 我首先在创建的列列表中移动了主键列( nameRed ),但这只是约定。 It could go second. 它可能会排名第二。
  2. You use the data type VARCHAR and SQlite will accept that, but be aware that it gets mapped to type TEXT, the maximum length will be ignored, and you will be able to store other data types in the column. 您使用数据类型VARCHAR,SQlite会接受,但是要注意,它已映射为TEXT类型,最大长度将被忽略,并且您将能够在该列中存储其他数据类型。 SQLite is a bit funny when it comes to data types (it has a very well thought-out system but it's quite different from most other SQL databases). 关于数据类型,SQLite有点可笑(它具有经过深思熟虑的系统,但与大多数其他SQL数据库有很大不同)。
  3. To make things more confusing, you are allowed to declare the PRIMARY KEY as a property of the column (although you can also do it after the list of columns as with the FOREIGN KEY). 为了使事情变得更加混乱,你允许申报的主键列的属性(虽然你也可以做到这一点列的列表与外键后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM