将DataTable转化为json

csharp 复制代码
using MySqlConnector;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MysqlConnectorDemo
{
    internal class Program
    {
        public static string GetDataFromUserTable()
        {
            string connectionString = "server=localhost;user id=root;password=***;port=3306;database=test;";
            string query = "select * from sys_user";
            using (MySqlConnection con =new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd=new MySqlCommand(query,con))
                {
                    con.Open(); 
                    MySqlDataReader reader = cmd.ExecuteReader();
                    DataTable dt=new DataTable();
                    dt.Load(reader);
                    string json = JsonConvert.SerializeObject(dt,Formatting.Indented);
                    return json;
                }
            }
        }
        static void Main(string[] args)
        {
            string json=GetDataFromUserTable();
            Console.WriteLine(json);
        }
    }
}
相关推荐
决斗小饼干1 小时前
序列化 JSON 时崩了?99% 是 EF 延迟加载惹的祸,三种解法拿走不谢
json
ZC跨境爬虫2 小时前
3D 地球卫星轨道可视化平台开发 Day9(AI阈值调控+小众卫星识别+低Token测试模式实战)
人工智能·python·3d·信息可视化·json
ZC跨境爬虫3 小时前
3D 地球卫星轨道可视化平台开发 Day6(SEC数据接口扩展实现)
前端·microsoft·3d·html·json·交互
Hello--_--World3 小时前
ES16:Set 集合方法增强、Promise.try、迭代器助手、JSON 模块导入 相关知识
开发语言·javascript·json
电商API&Tina7 小时前
【1688API接口】1688 开放平台 API 接入心得
java·开发语言·数据库·python·sql·json
智慧地球(AI·Earth)1 天前
用 Python 构建一个“记性好”的 AI 助手:JSON本地存储和向量检索
人工智能·python·json
五阿哥永琪3 天前
MySQL 中 VARCHAR、TEXT 与 JSON 类型:区别、场景与选型指南
数据库·mysql·json
liliangcsdn3 天前
从长字符串中解析合法json结构的示例
json
ZC跨境爬虫3 天前
3D地球卫星轨道可视化平台开发Day2(轨道错位Bug修复+模块化结构优化)
前端·3d·html·json·bug
ZC跨境爬虫3 天前
3D 地球卫星轨道可视化平台开发 Day1(3D 场景、卫星渲染与筛选交互实现)
前端·3d·html·json·交互