【问题标题】:How to convert a MySQL query to JSON on C#如何在 C# 上将 MySQL 查询转换为 JSON
【发布时间】:2017-10-22 18:31:44
【问题描述】:

这是我的代码

我想知道如何在 C# 中显示 JSON 格式的以下查询以在 Web 服务中使用它

    public void GetEmpleadoJSON()
    {
        string server = "localhost", database = "ventas", user = "root", pass = "";
        MySqlConnection conectar = new MySqlConnection("server=" + server + "; database=" + database + "; Uid=" + user + "; pwd=" + pass + ";");
        conectar.Open();
        MySqlCommand command = conectar.CreateCommand();

        //consulta select
        command.CommandText = ("SELECT `nombre` FROM `cliente` WHERE id_cliente=901 ");
        command.Connection = conectar;
        MySqlDataReader reader = command.ExecuteReader();


        Empleado[] emps = new Empleado[] {
        new Empleado(){
            Id=101,
            Name=reader.ToString(),
            Salary=10000
        }

    };
       JavaScriptSerializer js = new JavaScriptSerializer();
       Context.Response.Write(js.Serialize(emps));
    }


}

}

【问题讨论】:

    标签: c# mysql json visual-studio


    【解决方案1】:

    您可以使用 Newtonsoft.Json 将您的输出转换为 JSON 格式。

    using Newtonsoft.Json;
    
    public void GetEmpleadoJSON()
        {
            string server = "localhost", database = "ventas", user = "root", pass = "";
            MySqlConnection conectar = new MySqlConnection("server=" + server + "; database=" + database + "; Uid=" + user + "; pwd=" + pass + ";");
            conectar.Open();
            MySqlCommand command = conectar.CreateCommand();
    
            //consulta select
            command.CommandText = ("SELECT `nombre` FROM `cliente` WHERE id_cliente=901 ");
            command.Connection = conectar;
            MySqlDataReader reader = command.ExecuteReader();
    
    
            Empleado[] emps = new Empleado[] {
        new Empleado(){
            Id=101,
            Name=reader.ToString(),
            Salary=10000
        }
    
    };
            var jsonString = JsonConvert.SerializeObject(emps);
            Context.Response.Write(jsonString);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2021-07-04
      • 2020-09-19
      • 1970-01-01
      • 2021-04-03
      • 2015-03-22
      • 2015-04-21
      相关资源
      最近更新 更多