[英]How to store and retrieve an array to and from SQL database table in c#
[英]How to store a result of type integer array from database to an array in C#?
我正在使用 postgresql 作為數據庫,並且我有一個名為 foodsIds 的列,它的類型是整數數組。
我正在進行以下 SQL 查詢。
// Specify connection
NpgsqlConnection conn = new NpgsqlConnection(
"Server=127.0.0.1;" +
"User Id=username;" +
"Password=password;" +
"Database=db;" +
"Port=3500");
conn.Open();
// Define a query
NpgsqlCommand cmd = new NpgsqlCommand($"SELECT catsids FROM restaurants WHERE id = {Properties.Settings.Default.ResId.ToString()}", conn);
// Execute a query
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
/*
I WANT TO INSERT CODE HERE
*/
}
// Close connection
conn.Close();
現在我知道結果是一個整數數組,我想將它存儲在一個數組中,以便我可以使用其中的值。
知道怎么做嗎?
嘗試這樣的事情:
List<int> myList = new List<int>();
while(dr.Read())
{
int newInt = int.Parse(dr["catsids"].ToString());
//push to list or array here e.g.
myList.Add(newInt);
}
存在從 PG 數組到 C# 數組的直接映射。 您可以簡單地將返回的 object 轉換為數組
int[] result;
if (dr.Read())
{
result = (int[])dr.GetValue(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.