Answer the question
In order to leave comments, you need to log in
How to fill an array with data in C#?
I was advised in C# to use classes to describe the data structure. Here is a description of my data.
namespace DBSync.Model
{
public class UserData
{
public string Id { get; set; }
public string Guid { get; set; }
public string Name { get; set; }
public byte[] UserBlob { get; set; }
public string FL { get; set; }
};
}
public UserData GetData()
{
try
{
string sql = @"SELECT id, guid, username, userblob, ""FL"" FROM ""USERS"" WHERE ""FL""=10;";
NpgsqlCommand command = new NpgsqlCommand(sql, (NpgsqlConnection)Connection);
NpgsqlDataReader dr = command.ExecuteReader(); // here exception
if (!dr.HasRows)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] PostgreSQL do not have data with FL=10");
Console.ResetColor();
}
int i = 0;
while (dr.Read())
{
// UserData ud = new UserData();
ud.Id = dr[0].ToString();
ud.Guid = (dr[1].ToString());
ud.Name = (dr[2].ToString());
ud.UserBlob = (byte[])dr[3];
ud.FL = dr[4].ToString();
i++;
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Syncronisated PG->SQLite rows: {0}", i);
Console.ResetColor();
dr.Dispose(); // releases connection
try
{
sqllite.Connect();
sqllite.InsertData(ud);
string sqlUpdate = @"UPDATE ""USERS"" SET ""FL""=11 WHERE ""FL""=10;";
//NpgsqlCommand commandUpdate = new NpgsqlCommand(sql, (NpgsqlConnection)Connection);
NpgsqlCommand cmd = new NpgsqlCommand(sqlUpdate, (NpgsqlConnection)Connection);
cmd.ExecuteNonQuery();
if (i > 0)
{
Console.WriteLine("Flags in PostgreSQL set to 11 (waiting for sync)");
}
sqllite.CloseConnect();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Can't insert data to SQLite");
}
}
catch (Exception e)
{
Console.WriteLine("SelectDataForSync function");
Console.WriteLine(e.Message);
}
return ud;
}
Answer the question
In order to leave comments, you need to log in
you need to use List
For each entry create a new instance and add (Add() method) it to the list
UPD: something like this
List<UserData> usersList = new List<UserData>(); //создали список
while (dr.Read())
{
UserData ud = new UserData(); //создаем один экземпляр
ud.Id = dr[0].ToString(); //наполняем его
ud.Guid = (dr[1].ToString());
ud.Name = (dr[2].ToString());
ud.UserBlob = (byte[])dr[3];
ud.FL = dr[4].ToString();
usersList.Add(ud); //добавляем в список
}
int usersCount = usersList.Count; //количество элементов в списке
Console.WriteLine("[INFO] Syncronisated PG->SQLite rows: {0}", usersCount);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question