我在这里没什么问题。我尝试使用SqlDataReader从数据库中读取数据。代码是这样的:
internal static User GetUser(string login)
{
SqlConnection conn = new SqlConnection(DataBaseUtility.ConnectionString);
conn.Open();
string sql = "SELECT * FROM BookMenagerDB.dbo.users";
//where UserLogin like @login
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@login", login);
User user = new User();
SqlDataReader sqlDataReader = cmd.ExecuteReader();
user.Id = (int)sqlDataReader["UserId"];
user.Login = sqlDataReader["UserLogin"].ToString();
user.PasswordHash = sqlDataReader["UserPassword"].ToString();
user.Salt = (byte[])sqlDataReader["UserPasswordSalt"];
return user;
}
catch (SqlException ex)
{
MessageBox.Show("GetUser fail");
}
conn.Close();
return new User();
}
我尝试执行sql查询,但获取了数据,但行“ user.Id =(int)sqlDataReader [“ UserId”];“告诉我sqlDataReader中没有数据。 我不知道是什么问题。
答案 0 :(得分:3)
您需要在SqlDataReader上调用Read()
函数,以将读取器前进到数据库中的第一条记录或下一条记录。另外,您应该使用处置释放连接和资源。
public User GetUser(string login)
{
User user = new User();
const string sql = "SELECT * FROM BookMenagerDB.dbo.users";
using (SqlConnection connection = new SqlConnection(DataBaseUtility.ConnectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
command.Parameters.AddWithValue("@login", login);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
user.Id = (int)reader["UserId"];
user.Login = reader["UserLogin"].ToString();
user.PasswordHash = reader["UserPassword"].ToString();
user.Salt = (byte[])reader["UserPasswordSalt"];
}
}
}
return user;
}
答案 1 :(得分:0)
在ExecuteReader()
之后,您应该Read()
来获取记录:
User user = new User();
SqlDataReader sqlDataReader = cmd.ExecuteReader();
if(sqlDataReader.Read())
{
user.Id = (int)sqlDataReader["UserId"];
user.Login = sqlDataReader["UserLogin"].ToString();
user.PasswordHash = sqlDataReader["UserPassword"].ToString();
user.Salt = (byte[])sqlDataReader["UserPasswordSalt"];
}