C#新建一个SQLite数据表同时设置ID为主键所有列不允许有空值
在C#中,可以使用System.Data.SQLite库来操作SQLite数据库。以下是一个示例代码,用于新建一个SQLite数据表,设置ID为主键,并且所有列不允许有空值:
using System;
using System.Data.SQLite;
namespace SQLiteExample
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=mydatabase.db;Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "CREATE TABLE MyTable (ID INTEGER PRIMARY KEY, Column1 TEXT NOT NULL, Column2 INTEGER NOT NULL, Column3 REAL NOT NULL)";
command.ExecuteNonQuery();
}
connection.Close();
}
Console.WriteLine("Table created successfully.");
Console.ReadLine();
}
}
}
在上述代码中,我们首先创建了一个SQLite连接,并打开了连接。然后使用SQLiteCommand对象执行了CREATE TABLE语句来创建名为"MyTable"的数据表。在CREATE TABLE语句中,我们使用了"ID INTEGER PRIMARY KEY"来设置ID列为主键,"Column1 TEXT NOT NULL"来设置Column1列为不允许为空的文本类型,"Column2 INTEGER NOT NULL"来设置Column2列为不允许为空的整数类型,"Column3 REAL NOT NULL"来设置Column3列为不允许为空的实数类型。
最后,我们关闭了数据库连接,并输出了"Table created successfully."来表示数据表创建成功。
请注意,你需要将"mydatabase.db"替换为你实际的SQLite数据库文件路径。如果该文件不存在,它将会被创建
原文地址: https://www.cveoy.top/t/topic/hJWg 著作权归作者所有。请勿转载和采集!