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#

相关推荐
下页、再停留5 小时前
【C#桌面客户端系列学习-15】生成可视化图表之折线图、柱状图、饼状图
开发语言·c#
zyseo85 小时前
谷歌SEO 准首页词挖掘脚本:找出排在第 8-20 名的隐藏流量
大数据·数据库·人工智能
xiaogai_gai7 小时前
仅查询策略实战:从金蝶云·星空旗舰版定时拉取收料通知单
大数据·数据库·python
数据工匠老o7 小时前
异构数据库DDL同步:260条链路的结构变更自动适配方案
数据库·架构
这个DBA有点耶8 小时前
银行业市占率最高的国产数据库是谁?先搞清楚“市占率”的四种口径
数据库·程序员·架构
用户6279947182629 小时前
南大通用GBase 8a之基于审计日志的冷温热数据分析
数据库
数据库小学妹9 小时前
数据库运维五级成熟度:监控、备份、高可用怎么串起来
运维·数据库·监控
一个天蝎座的程序猿9 小时前
为了给报表提速,我把金仓KES的列存储折腾了个遍:聊聊KES的技术能力
数据库
飞越未来云城的霓虹飞猪9 小时前
AI 数据库地图:从 PostgreSQL 到向量数据库,一次看懂 AI 时代的数据底座
数据库
不像程序员的程序媛9 小时前
导出mysql数据结构
数据库·mysql