我想使用SqlDataReader
用我的SQL Server数据库中的数据填充用户数组。
这是我到目前为止的代码:
public struct User
{
public int id;
public string log;
public string password;
public User (int id1,string s, s2)
{
id=id1;
log =s;
password=s2;
}
}
User[] al = new User[50];
int i=0;
using (SqlConnection connection = new SqlConnection("string")
{
connection.Open();
SqlCommand command = new SqlCommand("Select [UserName], [Password]. from [TaUser]", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// populate the al array with the datas from the 3 columns : ID, UserName, Password
}
}
connection.Close();
}
我知道,如果我有一个简单的数组列表,我可以只做al.Add("")
,然而,当涉及到结构数组时,我很难做到。
发布于 2018-05-30 07:36:56
你的代码中有很多错误。
首先,你的用户构造函数无效,它应该是:
public User(int id1, string s, string s2)
其次,您的查询不返回用户id。
第三,使用List而不是array可能更好。
有了所有这些,这应该是可行的
List<User> userList = new List<User>() ;
using (SqlConnection connection = new SqlConnection("string")
{
connection.Open();
SqlCommand command = new SqlCommand("Select [Id], [UserName], [Password]. from [TaUser]", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var id = reader.GetInt32(0);
var userName = reader.GetString(1);
var pwd = reader.GetString(2);
var user = new User(id, userName, pwd);
userList.Add(user);
}
}
connection.Close();
// if you really need an array, do it here
var al = userList.ToArray()
发布于 2018-05-30 07:29:26
我建议这样做:
SqlDataReader dataReader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);
然后像这样读出DataTable:
string name = dataTable.Rows[0]["UserName"] as string;
然后用收集到的信息填充你的用户结构。任务完成了吗?
https://stackoverflow.com/questions/50594250
复制相似问题