C#连接MySql数据库 (ASP.NET API)

main方法调用连接

using System;

using MySql.Data.MySqlClient;

class Program

{

static void Main(string\[\] args)

{

string connectionString = "server=localhost;database=***;username=***;password=****";

using (MySqlConnection connection = new MySqlConnection(connectionString))

{

//try

//{

// connection.Open();

// // 执行数据库操作

// Console.WriteLine("连接成功!");

//}

//catch (MySqlException ex)

//{

// Console.WriteLine("数据库连接失败: " + ex.Message);

//}

try

{

connection.Open();

string query = "SELECT * FROM aaa";

MySqlCommand cmd = new MySqlCommand(query, connection);

MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

{

Console.WriteLine(reader"SHORI_NEN".ToString());

}

reader.Close();

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

connection.Close();

}

}

}

上面是练习 下面是api重点哦

1.Program.cs 文件添加

添加对配置文件的引用

//builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

配置连接字符串

//var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

添加数据库上下文服务

//builder.Services.AddDbContext<StudentContext>(options =>

// options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))

//);

或者

builder.Services.AddDbContext<StudentContext>(options =>

options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version())));

主要是引入json文件

2.appsettings.json

"ConnectionStrings": {

"DefaultConnection": "server=localhost;database=****;username=*****;password=******"

},

Program里的"DefaultConnection"要和json一致哦

这时候就已经配置好连接了

3.新建Moudels 文件夹

创建学生Student

namespace TodoApi.Models

{

public class Student

{

Key

public int Id { get; set; }

//大小写都可以 带下划线的需要和数据库一致 也可以配置(自己百度)

public string Name { get; set; } = String.Empty;

public string Age { get; set; } = String.Empty;

}

}

数据库记得建表

CREATE TABLE `student` (

`Id` int NOT NULL COMMENT 'OID',

`Name` varchar(2) NOT NULL COMMENT '名称',

`Age` varchar(1) NOT NULL COMMENT '年龄'

)

4.创建StudentContext文件

using Microsoft.EntityFrameworkCore;

using WebApplication777.Models;

namespace TodoApi.Models

{

public class StudentContext : DbContext

{

public StudentContext(DbContextOptions<StudentContext> options) : base(options)

{

}

public DbSet<Student> Students { get; set; }

public DbSet<MsgMst> MsgMsts { get; set; }

//OnModelCreating ToTable为了映射数据库

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

//entity(自己的表) ToTable (填写数据库的名字)

modelBuilder.Entity<Student>().ToTable("student");

modelBuilder.Entity<MsgMst>().ToTable("msg_mst");

}

}

}

5.controller

建立StudentController

using Microsoft.AspNetCore.Mvc;

using TodoApi.Models;

using WebApplication777.Models;

namespace TodoApi.Controllers

{

Route("api/\[controller\]")

ApiController

public class StudentController : ControllerBase

{

private readonly StudentContext _context;

public StudentController(StudentContext context)

{

_context = context;

}

HttpGet("{id}")

public async Task<ActionResult<Student>> Get(int id)

{

var studentsId = await _context.Students.FindAsync(id);

if (studentsId == null)

{

return NotFound();

}

return studentsId;

}

}

}

这时候就可以查询数据库啦

记得点赞哈

第一次学c#

相关推荐
一只鹿鹿鹿1 小时前
政务外网整体设计方案(PPT)
大数据·数据库·web安全·系统安全·流程图·政务
2603_965148112 小时前
社区与学习资源:从入门到精通的API选品学习路径
数据库·人工智能·python·学习·数据挖掘
AI砖家2 小时前
安全进入 Agent Loop:2027 年 Coding Agent 的决胜点
数据库·安全·codex·vibecoding
wangqiaowq2 小时前
SQL server C盘空间占满的处理
数据库·sql
文人sec2 小时前
SQL基础入门笔记 | 从零基础到掌握核心查询语句
数据库·笔记·sql
数字新视界2 小时前
机房动环监控提升运维效率
大数据·服务器·数据库·动环监控系统·动力与环境监控系统
SelectDB技术团队2 小时前
冷热分层从建到验:Storage Policy 创建、表级与分区级绑定、SHOW TABLETS 验证的完整命令
大数据·数据库·elasticsearch·搜索引擎·数据分析·apache doris·冷热分层
lambo mercy4 小时前
Day3:结构化输出
java·数据库·oracle
派小心.4 小时前
小程序分享链路中来源参数的传递校验
大数据·前端·数据库·人工智能·小程序·数据分析
Είναι η κοπέλα4 小时前
向量数据库与嵌入模型:Chroma/FAISS/Milvus 选型
数据库·milvus·faiss