成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

NetCore使用SQLite數(shù)據(jù)庫入門基礎(chǔ)

數(shù)據(jù)庫 其他數(shù)據(jù)庫
本文將分模塊講解如何使用SQLite數(shù)據(jù)庫,包括數(shù)據(jù)庫連接、創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)和更新數(shù)據(jù)等方面。以及使用Sqltie構(gòu)建案例實戰(zhàn)。

SQLite是一種輕量級的嵌入式數(shù)據(jù)庫引擎,廣泛應(yīng)用于各種開發(fā)項目中。System.Data.SQLite庫,提供了許多用于操作數(shù)據(jù)庫的功能和API。本文將分模塊講解如何使用SQLite數(shù)據(jù)庫,包括數(shù)據(jù)庫連接、創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)和更新數(shù)據(jù)等方面。以及使用Sqltie構(gòu)建案例實戰(zhàn)。

SQLite基本用法

1、引用和連接數(shù)據(jù)庫

首先,在你的項目中引入 System.Data.SQLite 命名空間。然后,創(chuàng)建一個 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)鍵字用于自動遞增生成主鍵值。

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案例實戰(zhàn)

以下是一個使用 ASP.NET Core Web API 和 SQLite 數(shù)據(jù)庫構(gòu)建完整權(quán)限管理系統(tǒng)的代碼示例:

1、創(chuàng)建項目

首先,創(chuàng)建一個 ASP.NET Core Web API 項目。

dotnet new webapi -n PermissionManagementSystem
cd PermissionManagementSystem

2、添加依賴項

在項目的 .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>

運行以下命令以安裝這些依賴項:

dotnet restore

3、創(chuàng)建數(shù)據(jù)模型

在項目中創(chuàng)建一個名為 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; }
}

同時,創(chuàng)建一個名為 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)建一個名為 AppDbContext 的數(shù)據(jù)庫上下文類,用于與 SQLite 數(shù)據(jù)庫進行交互。

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)建一個名為 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();
    }
}

這個控制器包含了用于處理權(quán)限的 CRUD 操作的相應(yīng)動作方法。

6、注冊服務(wù)和啟動應(yīng)用程序

在 Startup.cs 中注冊數(shù)據(jù)庫上下文服務(wù),并啟動應(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īng)用程序

運行以下命令啟動應(yīng)用程序:

dotnet run

現(xiàn)在,你可以通過發(fā)送 HTTP 請求到 /api/permissions 路由來使用這個權(quán)限管理系統(tǒng)。

這是一個簡單的示例,展示了如何使用 ASP.NET Core Web API 和 SQLite 數(shù)據(jù)庫構(gòu)建一個基本的權(quán)限管理系統(tǒng)。你可以根據(jù)實際需求擴展和優(yōu)化這些代碼,并添加身份驗證和授權(quán)等功能來完善系統(tǒng)。

責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2019-08-15 07:00:54

SQLite數(shù)據(jù)庫內(nèi)存數(shù)據(jù)庫

2012-03-06 09:50:24

Android SQLAndroidSQLite3

2011-08-02 16:16:08

iPhone開發(fā) SQLite 數(shù)據(jù)庫

2013-03-27 09:47:01

Android開發(fā)SQAndroid SDK

2011-07-27 10:16:41

iPhone SQLite 數(shù)據(jù)庫

2019-10-12 15:06:02

MySQL數(shù)據(jù)庫命令

2017-07-12 09:20:42

SQLite數(shù)據(jù)庫移植

2011-07-20 12:34:49

SQLite數(shù)據(jù)庫約束

2021-09-12 17:25:12

SQLite數(shù)據(jù)庫

2011-08-04 18:00:47

SQLite數(shù)據(jù)庫批量數(shù)據(jù)

2024-10-28 16:31:03

2023-11-08 08:32:16

2024-02-28 08:06:17

2011-07-05 10:16:16

Qt 數(shù)據(jù)庫 SQLite

2011-08-24 13:49:45

Access數(shù)據(jù)庫轉(zhuǎn)化

2018-07-13 09:20:30

SQLite數(shù)據(jù)庫存儲

2019-11-20 09:08:46

PostgreSQL數(shù)據(jù)庫

2009-12-07 17:33:44

PHP SQlite數(shù)

2010-01-27 18:33:16

Android SQL

2011-08-30 14:15:34

QTSQLite數(shù)據(jù)庫
點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 国产精品一区在线观看 | 国产欧美精品一区 | 亚洲逼院| 国产黑丝在线 | 久热国产精品 | 国产综合精品一区二区三区 | 久久国产成人午夜av影院武则天 | 91亚洲国产亚洲国产 | 99视频在线看 | 无毛av | 欧美精品网 | 麻豆亚洲 | 日韩毛片免费视频 | 久久精品免费一区二区三 | 色婷婷久久久久swag精品 | 在线视频亚洲 | 成人福利在线 | 91视频在线观看 | 国产一区二区三区在线 | 亚洲天堂中文字幕 | 欧美激情精品久久久久久变态 | 亚州精品天堂中文字幕 | 国产成人高清成人av片在线看 | 美人の美乳で授乳プレイ | 久久i| 亚洲国产精品久久久久秋霞不卡 | 国产精品99免费视频 | 久久黄色网 | 日韩高清成人 | 91精品久久久久久久久 | 亚洲一区视频在线 | 欧美jizzhd精品欧美巨大免费 | 国产成人精品一区二 | 国产精品久久久久永久免费观看 | 久久精品二区 | 国产黄色大片网站 | 大乳boobs巨大吃奶挤奶 | 国产在线一区观看 | 黄色精品 | 精品久久av| 91在线资源 |