NetCore使用SQLite數(shù)據(jù)庫入門基礎(chǔ)
SQLite是一種輕量級的嵌入式數(shù)據(jù)庫引擎,廣泛應(yīng)用于各種開發(fā)項(xiàng)目中。System.Data.SQLite庫,提供了許多用于操作數(shù)據(jù)庫的功能和API。本文將分模塊講解如何使用SQLite數(shù)據(jù)庫,包括數(shù)據(jù)庫連接、創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)和更新數(shù)據(jù)等方面。以及使用Sqltie構(gòu)建案例實(shí)戰(zhàn)。
SQLite基本用法
1、引用和連接數(shù)據(jù)庫
首先,在你的項(xiàng)目中引入 System.Data.SQLite 命名空間。然后,創(chuàng)建一個(gè) SQLiteConnection 對象,并使用它連接到 SQLite 數(shù)據(jù)庫。
using System.Data.SQLite;
// 創(chuàng)建連接對象
SQLiteConnection connection = new SQLiteConnection("Data Source=mydatabase.db;Version=3;");
// 打開連接
connection.Open();
// 關(guān)閉連接
connection.Close();
2、創(chuàng)建表
在連接數(shù)據(jù)庫后,你可以使用 SQLiteCommand 對象執(zhí)行 SQL 語句來創(chuàng)建表。
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "CREATE TABLE IF NOT EXISTS Employees (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INT);";
command.ExecuteNonQuery();
}
這里我們使用 CREATE TABLE IF NOT EXISTS 語句來創(chuàng)建名為 "Employees" 的表。該表包含三列:Id、Name 和 Age。注意,AUTOINCREMENT 關(guān)鍵字用于自動(dòng)遞增生成主鍵值。
3、插入數(shù)據(jù)
使用 INSERT INTO 語句,可以向表中插入數(shù)據(jù)。
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "INSERT INTO Employees (Name, Age) VALUES ('John Doe', 25);";
command.ExecuteNonQuery();
}
這里我們將名為 "John Doe" 的員工信息插入到 "Employees" 表中。
4、查詢數(shù)據(jù)
使用 SELECT 語句,可以從表中檢索數(shù)據(jù)。
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "SELECT * FROM Employees;";
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
int age = reader.GetInt32(2);
Console.WriteLine($"ID: {id}, Name: {name}, Age: {age}");
}
}
}
這里我們使用 SELECT * 來查詢 "Employees" 表中的所有數(shù)據(jù),并將結(jié)果打印到控制臺。
5、更新和刪除數(shù)據(jù)
使用 UPDATE 和 DELETE 語句,可以更新和刪除表中的數(shù)據(jù)。
// 更新數(shù)據(jù)
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "UPDATE Employees SET Age = 30 WHERE Name = 'John Doe';";
command.ExecuteNonQuery();
}
// 刪除數(shù)據(jù)
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "DELETE FROM Employees WHERE Id = 1;";
command.ExecuteNonQuery();
}
這里我們使用 UPDATE 語句將名為 "John Doe" 的員工年齡更新為 30,并使用 DELETE 語句刪除主鍵為 1 的員工數(shù)據(jù)。
SQLite案例實(shí)戰(zhàn)
以下是一個(gè)使用 ASP.NET Core Web API 和 SQLite 數(shù)據(jù)庫構(gòu)建完整權(quán)限管理系統(tǒng)的代碼示例:
1、創(chuàng)建項(xiàng)目
首先,創(chuàng)建一個(gè) ASP.NET Core Web API 項(xiàng)目。
dotnet new webapi -n PermissionManagementSystem
cd PermissionManagementSystem
2、添加依賴項(xiàng)
在項(xiàng)目的 .csproj 文件中,添加對Microsoft.EntityFrameworkCore.Sqlite 和 Microsoft.EntityFrameworkCore.Design 的依賴。
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
運(yùn)行以下命令以安裝這些依賴項(xiàng):
dotnet restore
3、創(chuàng)建數(shù)據(jù)模型
在項(xiàng)目中創(chuàng)建一個(gè)名為 Permission 的數(shù)據(jù)模型類,用于表示權(quán)限。
using System.ComponentModel.DataAnnotations;
public class Permission
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
// 其他屬性...
// 導(dǎo)航屬性
public ICollection<User> Users { get; set; }
}
同時(shí),創(chuàng)建一個(gè)名為 User 的數(shù)據(jù)模型類,用于表示用戶。
using System.ComponentModel.DataAnnotations;
public class User
{
[Key]
public int Id { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
// 其他屬性...
// 導(dǎo)航屬性
public ICollection<Permission> Permissions { get; set; }
}
4、配置數(shù)據(jù)庫上下文
創(chuàng)建一個(gè)名為 AppDbContext 的數(shù)據(jù)庫上下文類,用于與 SQLite 數(shù)據(jù)庫進(jìn)行交互。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace PermissionManagementSystem
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Permission> Permissions { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=permissions.db");
}
}
}
這里我們使用 SQLite 數(shù)據(jù)庫作為數(shù)據(jù)存儲,并指定數(shù)據(jù)庫文件為 permissions.db。
5、創(chuàng)建控制器
創(chuàng)建一個(gè)名為 PermissionsController 的控制器,用于處理權(quán)限相關(guān)的 HTTP 請求。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
[ApiController]
[Route("api/[controller]")]
public class PermissionsController : ControllerBase
{
private readonly AppDbContext _dbContext;
public PermissionsController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public ActionResult<IEnumerable<Permission>> GetPermissions()
{
var permissions = _dbContext.Permissions.ToList();
return Ok(permissions);
}
[HttpPost]
public ActionResult<Permission> CreatePermission(Permission permission)
{
_dbContext.Permissions.Add(permission);
_dbContext.SaveChanges();
return CreatedAtAction(nameof(GetPermission), new { id = permission.Id }, permission);
}
[HttpGet("{id}")]
public ActionResult<Permission> GetPermission(int id)
{
var permission = _dbContext.Permissions.Find(id);
if (permission == null)
{
return NotFound();
}
return Ok(permission);
}
[HttpPut("{id}")]
public IActionResult UpdatePermission(int id, Permission permission)
{
if (id != permission.Id)
{
return BadRequest();
}
_dbContext.Entry(permission).State = EntityState.Modified;
_dbContext.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeletePermission(int id)
{
var permission = _dbContext.Permissions.Find(id);
if (permission == null)
{
return NotFound();
}
_dbContext.Permissions.Remove(permission);
_dbContext.SaveChanges();
return NoContent();
}
}
這個(gè)控制器包含了用于處理權(quán)限的 CRUD 操作的相應(yīng)動(dòng)作方法。
6、注冊服務(wù)和啟動(dòng)應(yīng)用程序
在 Startup.cs 中注冊數(shù)據(jù)庫上下文服務(wù),并啟動(dòng)應(yīng)用程序。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace PermissionManagementSystem
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(_configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Configure the HTTP request pipeline.
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
7、配置連接字符串
在 appsettings.json 文件中,添加連接字符串配置。
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=permissions.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
這里我們指定了數(shù)據(jù)庫連接字符串為 Data Source=permissions.db。
8、運(yùn)行應(yīng)用程序
運(yùn)行以下命令啟動(dòng)應(yīng)用程序:
dotnet run
現(xiàn)在,你可以通過發(fā)送 HTTP 請求到 /api/permissions 路由來使用這個(gè)權(quán)限管理系統(tǒng)。
這是一個(gè)簡單的示例,展示了如何使用 ASP.NET Core Web API 和 SQLite 數(shù)據(jù)庫構(gòu)建一個(gè)基本的權(quán)限管理系統(tǒng)。你可以根據(jù)實(shí)際需求擴(kuò)展和優(yōu)化這些代碼,并添加身份驗(yàn)證和授權(quán)等功能來完善系統(tǒng)。