[英]C# SQL data from DataTable to Array
I have a program where logged in users can upload/dowload files. 我有一个程序,登录的用户可以在其中上传/下载文件。 I want a query when a user is logged in, and store the data in an array.
我想在用户登录时查询,并将数据存储在数组中。 Here's my code:
这是我的代码:
string query = "SELECT * FROM Login;";
var valami = new DataTable();
var con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Roland\Desktop\IBCONTROLL\BIZT.MENTÉS\program_1.7\db_connect_ver_1\login.mdf;Integrated Security=True");
var sda = new SqlDataAdapter(query, con);
sda.Fill(valami);
var result = new string[valami.Columns.Count];
DataRow dr = valami.Rows[1];
for (var i = 0; i < dr.ItemArray.Length; i++)
{
result[i] = dr[i].ToString();
}
foreach (var t in result)
{
Console.WriteLine(t);
}
The problem is that this is making an 1 dimension array, but I need a two dimension array, and use it later just as a table. 问题在于,这是一个1维数组,但是我需要一个2维数组,以后将其用作表。
Can you please help me fix this code? 您能帮我解决此代码吗?
You can store the DataTable
instead of storing it as a 2-D array. 您可以存储
DataTable
而不是将其存储为二维数组。 There are multiple benefits to it. 它有很多好处。 You can not only access the data by column name (which you cannot do in a 2-d array), but you will also have all metadata related to the query you fired, in the
DataTable
. 您不仅可以按列名访问数据(在二维数组中不能这样做),而且在
DataTable
还将具有与您触发的查询相关的所有元DataTable
。 Note that storing this metadata has a small memory overhead. 请注意,存储此元数据的内存开销很小。
To access a given element you can write DataTable.Rows[rowNumber][columnNumber]
or DataTable.Rows[rowNumber][columnName]
要访问给定元素,您可以编写
DataTable.Rows[rowNumber][columnNumber]
或DataTable.Rows[rowNumber][columnName]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.