我从数据库中获取数据的问题,因为我是c#语言的新手。我认为ExecuteReader应该检索所有行。顺便说一下,我无法访问像对象一样的数据。和 reader.GetString(0)它只返回数组对象的索引。
c#中的任何属性是否都可以访问数据库中的行?
我正在寻找解决这个问题的答案。我已经拨出了帮助!
以下是我目前的代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Npgsql;
namespace Sample.Controllers
{
public class HomeController : Controller
{
public string Index()
{
var connString = "Host=localhost;Username=postgres;Password=123456;Database=dotnet_core_db";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// Retrieve all rows
using (var cmd = new NpgsqlCommand("SELECT * FROM Persons", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
Console.WriteLine(reader.GetString(1));
Console.WriteLine(reader.GetString(2));
Console.WriteLine(reader.GetString(3));
Console.WriteLine(reader.GetString(4));
ViewData["connString"] = connString;
}
}
return connString;
}
public IActionResult Error()
{
ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
return View();
}
}
}
期望结果
{
{
id: 92,
name: "foo",
last_name: "bar",
address: "adress Of foo",
city: "city of foo"
},
{
id: 872,
name: "foo1",
last_name: "bar 2",
address: "address of foo1",
city: "city of foo1"
}
}
答案 0 :(得分:0)
数据检索没问题。你需要的是一个json写作包。考虑像json.net这样的库来缓解这项工作。
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
while (dataReader.Read())
{
writer.WriteStartObject();
for (int i = 0; i < dataReader.fieldCount; ++i)
{
writer.WritePropertyName(dataReader.GetName(i));
writer.WriteValue(dataReader.GetValue(i).ToString());
}
writer.WriteEndObject();
}
}
fileWriter.Write(sb.ToString());
答案 1 :(得分:0)
你可以像下面一样
using (var cmd = new NpgsqlCommand("SELECT * FROM Persons", conn))
{
using (var reader = cmd.ExecuteReader())
{
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
columns.Add(reader.GetName(i));
JsonArrayCollection jsonArray = new JsonArrayCollection();
while (reader.Read())
{
JsonObjectCollection jsonObject = new JsonObjectCollection();
for(string columnName in columns)
jsonObject.Add(new JsonStringValue(columnName, reader[columnName]));
jsonArray.Add(jsonObject);
}
}
}
写在记事本中,请原谅任何编译错误。
注意:您可以使用任何json库,只会改变语法。