1

I was trying to check whether there is any rows having username and friend username in database table. If any then I have to take the friendship status in a string and will return that string.
Here is the code:

string query = "Select * from tblfriend where username = '" + username + "'and friend = '" + friendname + "'";

SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(reader);

rows = dt.Rows.Count;

if (rows > 0)
{
    friendship = reader["friendshipstatus"].ToString();
}

But it gives a error message:

Invalid Call to call MetaData when reader is closed. Can you guys please give a hint?

4

3 回答 3

0

由于您是从同一个阅读器加载 DataTable,它可能会在加载完成后关闭。

作为侧节点,您最好使用参数,使用语句等,如下所示

string queryString = "Select [friendshipstatus] from [tblfriend] where [username] = @username and [friend] = @friend";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
    command.Parameters.AddWithValue("@username", username);
    command.Parameters.AddWithValue("@friend", friendname );

    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        if(reader.Read()) // you have matching record if this condition true 
        {
            friendship = reader.GetString(0); // get the value of friendshipstatus 
        }
    }
}
于 2013-08-27T04:39:18.893 回答
0

您正在使用阅读器来填充数据表,然后当它已经被用于此时 - 尝试再次使用它。

有更好的方法可以从 db 中检索单个值(查找 ExecuteScalar),但要使您当前的代码正常工作,请将最后一行替换为

friendship = dt.rows[0].["friendshipstatus"].ToString()

这将从您填充的数据表中获取数据,而不是从封闭的阅读器中获取数据。

于 2013-08-27T04:42:30.180 回答
0

如果要将数据读入表中,则应使用 dataadapter

DataTable dt = new DataTable();
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(query, con))
{
   // Use DataAdapter to fill DataTable     
   a.Fill(dt);
   // read data here
}
rows = dt.Rows.Count;
if (rows > 0)
{
     friendship = dt.Rows[0]["friendshipstatus"].ToString();
}
于 2013-08-27T04:42:51.320 回答