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#

相关推荐
码码不爱我32 分钟前
学习笔记:Redis入门
数据库·redis·学习
熊出没39 分钟前
阿里云云原生数据库PolarDB和普通云数据库的区别?
数据库·阿里云·云原生
zhuiQiuMX1 小时前
SQL力扣
数据库·sql·leetcode
debug 小菜鸟2 小时前
MySQL 主从复制与一主多从架构实战详解
数据库·mysql·架构
远方16092 小时前
29-Oracle 23ai Flashback Log Placement(闪回日志灵活配置)
数据库·sql·oracle·database
꧁༺摩༒西༻꧂2 小时前
Windows安装Oracle19
数据库·oracle
CSharp精选营2 小时前
C# WinForms 实现打印监听组件
c#·winform·打印监听组件
代码老y2 小时前
前端开发中的可访问性设计:让互联网更包容
java·服务器·前端·数据库
weixin_438335402 小时前
MySQL索引优化:回表
数据库·mysql
SHUIPING_YANG3 小时前
tp3.1临时连接指定数据库,切片分类in查询,带过滤需要的数据
android·数据库