我有一点问题,但我无法弄清楚问题。所以我有一个DataReader
,我从我的数据库中读取数据。但问题是尽管我的数据库中有一个匹配的行,DataReader
仍然没有返回行。
我的数据库连接:
static private String _connectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=dboVids;User id=g;password=g;Connect Timeout=15;Encrypt=False";
static private SqlConnection _connection;
static Connection()
{
try
{
_connection = new SqlConnection(_connectionString);
Open();
}
catch (Exception ex)
{
switch (ex.HResult)
{
default:
throw;
}
}
}
我的方法:
static public SqlDataReader WeergevenRolPerUser(string userName)
{
try
{
Open();
SqlCommand command = new SqlCommand("select * from [dbo].[fnShowDatabaseRole]('@UserName')", _connection);
command.Parameters.AddWithValue("@UserName", userName);
SqlDataReader myReader = command.ExecuteReader();
myReader.Read();
return myReader;
}
catch (Exception ex)
{
switch (ex.HResult)
{
default:
throw;
}
}
}
Open()
方法:
private static void Open()
{
try
{
if (_connection.State != ConnectionState.Open)
_connection.Open();
}
catch (Exception ex)
{
switch (ex.HResult)
{
default:
throw;
}
}
}
这是我调用DataReader
:
private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataReader reader = null;
try
{
if (_username != "" && lstUsers.SelectedValue != null)
{
string user = lstUsers.SelectedValue.ToString();
reader = Database.Users.WeergevenRolPerUser(user);
if (reader.Read())
{
MessageBox.Show("unreachable");
var rol = reader.GetString(0);
if (rol == "gebruiker")
{
rdbUser.Checked = true;
}
}
}
}
catch (Exception ex)
{
switch (ex.HResult)
{
default:
throw;
}
}
finally
{
if (reader != null) reader.Close();
}
}
答案 0 :(得分:2)
我的猜测是你在阅读器对象上调用.Read()
两次,按照MSDN:
将SqlDataReader推进到下一条记录。
您在WeergevenRolPerUser
执行此操作一次,这将读取您希望返回的数据,再次在lstUsers_SelectedIndexChanged
中,您发现它不会读取任何内容,因为那里没有下一个进展记录。
如果我是你,我会更改WeergevenRolPerUser
以返回User
个对象。
static public User WeergevenRolPerUser(string userName)
{
try
{
using(var connection = new SqlConnection(/* connection string */))
{
connection.Open();
using(var command = new SqlCommand("select * from [dbo].[fnShowDatabaseRole]('@UserName')", connection))
{
command.Parameters.AddWithValue("@UserName", userName);
using(var myReader = command.ExecuteReader())
{
while(myReader.Read())
{
return new User
{
Username = myReader.GetString(/* column index */),
Role = myReader.GetString(/* column index */)
}
}
}
myReader.Close();
}
}
catch (SqlException ex)
{
throw;
}
}