当前位置: 首页 > news >正文

法律咨询微信网站建设中国建设行业峰会官方网站

法律咨询微信网站建设,中国建设行业峰会官方网站,造纸公司网站建设,辽宁建设工程信息网官网为什么打不开以下是一个使用 .NET Core API 连接 MySQL 数据库实现简单记事本功能的完整示例,包含创建、读取、更新和删除(CRUD)操作。 1. 创建 .NET Core Web API 项目 首先,打开命令行工具,使用以下命令创建一个新的 .NET Core…

以下是一个使用 .NET Core API 连接 MySQL 数据库实现简单记事本功能的完整示例,包含创建、读取、更新和删除(CRUD)操作。

1. 创建 .NET Core Web API 项目

首先,打开命令行工具,使用以下命令创建一个新的 .NET Core Web API 项目:

dotnet new webapi -n NotePadAPI
cd NotePadAPI

2. 安装 MySQL 数据库驱动

在项目目录下,使用以下命令安装 MySQL 数据库驱动:

dotnet add package MySqlConnector

3. 配置数据库连接字符串

打开 appsettings.json 文件,添加 MySQL 数据库连接字符串:

{"ConnectionStrings": {"DefaultConnection": "Server=localhost;Database=notepad;Uid=your_username;Pwd=your_password;"},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*"
}

请将 your_usernameyour_password 替换为你的 MySQL 用户名和密码。

4. 创建数据库和表

在 MySQL 中创建一个名为 notepad 的数据库,并创建一个名为 notes 的表:

CREATE DATABASE notepad;USE notepad;CREATE TABLE notes (id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255) NOT NULL,content TEXT NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

5. 创建数据模型

Models 文件夹下创建 Note.cs 文件:

using System;namespace NotePadAPI.Models
{public class Note{public int Id { get; set; }public string Title { get; set; }public string Content { get; set; }public DateTime CreatedAt { get; set; }}
}

6. 创建数据库上下文

Data 文件夹下创建 NoteContext.cs 文件:

using Microsoft.Data.SqlClient;
using MySqlConnector;
using NotePadAPI.Models;
using System.Collections.Generic;
using System.Data;namespace NotePadAPI.Data
{public class NoteContext{private readonly string _connectionString;public NoteContext(string connectionString){_connectionString = connectionString;}public List<Note> GetAllNotes(){var notes = new List<Note>();using (var connection = new MySqlConnection(_connectionString)){var query = "SELECT * FROM notes";var command = new MySqlCommand(query, connection);connection.Open();var reader = command.ExecuteReader();while (reader.Read()){notes.Add(new Note{Id = reader.GetInt32("id"),Title = reader.GetString("title"),Content = reader.GetString("content"),CreatedAt = reader.GetDateTime("created_at")});}reader.Close();}return notes;}public Note GetNoteById(int id){using (var connection = new MySqlConnection(_connectionString)){var query = "SELECT * FROM notes WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@id", id);connection.Open();var reader = command.ExecuteReader();if (reader.Read()){return new Note{Id = reader.GetInt32("id"),Title = reader.GetString("title"),Content = reader.GetString("content"),CreatedAt = reader.GetDateTime("created_at")};}reader.Close();}return null;}public void CreateNote(Note note){using (var connection = new MySqlConnection(_connectionString)){var query = "INSERT INTO notes (title, content) VALUES (@title, @content)";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@title", note.Title);command.Parameters.AddWithValue("@content", note.Content);connection.Open();command.ExecuteNonQuery();}}public void UpdateNote(Note note){using (var connection = new MySqlConnection(_connectionString)){var query = "UPDATE notes SET title = @title, content = @content WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@title", note.Title);command.Parameters.AddWithValue("@content", note.Content);command.Parameters.AddWithValue("@id", note.Id);connection.Open();command.ExecuteNonQuery();}}public void DeleteNote(int id){using (var connection = new MySqlConnection(_connectionString)){var query = "DELETE FROM notes WHERE id = @id";var command = new MySqlCommand(query, connection);command.Parameters.AddWithValue("@id", id);connection.Open();command.ExecuteNonQuery();}}}
}

7. 创建控制器

Controllers 文件夹下创建 NotesController.cs 文件:

using Microsoft.AspNetCore.Mvc;
using NotePadAPI.Data;
using NotePadAPI.Models;
using System.Collections.Generic;namespace NotePadAPI.Controllers
{[ApiController][Route("api/[controller]")]public class NotesController : ControllerBase{private readonly NoteContext _context;public NotesController(NoteContext context){_context = context;}[HttpGet]public ActionResult<IEnumerable<Note>> GetAllNotes(){var notes = _context.GetAllNotes();return Ok(notes);}[HttpGet("{id}")]public ActionResult<Note> GetNoteById(int id){var note = _context.GetNoteById(id);if (note == null){return NotFound();}return Ok(note);}[HttpPost]public ActionResult<Note> CreateNote(Note note){_context.CreateNote(note);return CreatedAtAction(nameof(GetNoteById), new { id = note.Id }, note);}[HttpPut("{id}")]public IActionResult UpdateNote(int id, Note note){if (id != note.Id){return BadRequest();}_context.UpdateNote(note);return NoContent();}[HttpDelete("{id}")]public IActionResult DeleteNote(int id){_context.DeleteNote(id);return NoContent();}}
}

8. 配置服务

打开 Program.cs 文件,配置数据库上下文:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NotePadAPI.Data;var builder = WebApplication.CreateBuilder(args);// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();// Configure database context
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddSingleton(new NoteContext(connectionString));var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();

9. 运行项目

在命令行中运行以下命令启动项目:

dotnet run

10. 测试 API

你可以使用 Postman 或其他 API 测试工具来测试以下接口:

  • 获取所有笔记GET http://localhost:5000/api/notes
  • 获取单个笔记GET http://localhost:5000/api/notes/{id}
  • 创建笔记POST http://localhost:5000/api/notes,请求体为 JSON 格式的笔记信息。
  • 更新笔记PUT http://localhost:5000/api/notes/{id},请求体为 JSON 格式的更新后的笔记信息。
  • 删除笔记DELETE http://localhost:5000/api/notes/{id}

通过以上步骤,你就可以实现一个简单的记事本 API,使用 .NET Core 连接 MySQL 数据库进行数据的 CRUD 操作。

http://www.dtcms.com/a/494149.html

相关文章:

  • 中山市 有限公司网站建设vps建设网站别人访问不了
  • 自学做网站做网站 商标分类
  • 网站百度指数分析浙江住房和城乡建设厅报名网站
  • 网站建设公司客户来源渠道建开发网站
  • 开源网站模板cmswordpress站内信插件
  • 宝宝投票网站怎么做展览搭建设计网站
  • 自己做购物网站怎么做小程序app开发软件定制
  • 网站建设中图片电话注册安全工程师报名条件和要求
  • wordpress新建站点seo下拉优化
  • 招商加盟网站建设目的站酷官网入口
  • wap网站设计方案太原网站建设价格低
  • 怎么搞一个服务器建设网站典型的电子商务网站有哪些
  • vue做网站的实例wordpress wiki知识库
  • 个人网站界面设计图片建站神器跟wordpress哪个好
  • 怎样自己弄一个网站网页版梦幻西游探案任务攻略
  • 企业建设网站有用么怎么做vip视频网站
  • 大型网站化方案关键词优化
  • 室内设计师联盟官网入口网站优化流程图
  • 做培训的都上哪些网站北京建设网站有哪些公司
  • 企业网站建设总结报告网站开发报价单明细
  • 哪个公司做公司网站好给公司建官网
  • 网站备案换主体吉林网络营销方式优化
  • 网站代码优化怎么做炫酷的网站
  • 绵阳 网站建设网页制作图片代码
  • 做鞋子出口需要作网站吗wordpress域名空间
  • 网站建设的总结与改进asp网站如何搭建
  • 如何做企业网站优化中山建站
  • 小程序登陆官网重庆seo
  • 怎样自己做免费网站购物网站建设要多少钱
  • 湖北省住房和城乡建设部网站肇庆建设工程备案的网站