简体   繁体   English

在完成阅读之前,请不要关闭SQL连接

[英]Don't close SQL connection until is has finished reading

I have the below code, which works, but is only reading the top row of the DB and then terminating. 我有下面的代码,它可以工作,但是只读取数据库的第一行,然后终止。 The array should hold 3 pieces of data, but it only holds one. 该数组应保存3个数据,但只能保存一个。

I think this is because it is not looping. 我认为这是因为它没有循环。

How do you say for the code to carry on running until it has no more data to read? 您如何说代码继续运行直到没有更多数据可读取?

SqlConnection conn1 = new SqlConnection(ssConnectionString);
conn1.Open();

SqlCommand command1 = conn1.CreateCommand();
command1.CommandText = "SELECT FeedURL FROM [dbo].[Feeds]";

rssFeeds.Add(command1.ExecuteScalar());

conn1.Close();

By default ExecuteScalar() will only ever return one value. 默认情况下, ExecuteScalar()将仅返回一个值。 You would need to create a DataReader , and then loop through the results using command1.ExecuteReader() 您将需要创建一个DataReader ,然后使用command1.ExecuteReader()遍历结果。

You can just use ExecuteReader for your problem. 您可以只使用ExecuteReader解决您的问题。 In this example that I took from MSDN is consuming the connection with using statement because SqlConnection class has some unmanaged resources. 在本例中,我从MSDN取得的示例正在使用using语句来消耗连接,因为SqlConnection类具有一些非托管资源。 If you have more questions about using and Finalizers also check here . 如果您对使用和终结器还有其他疑问,请在此处检查。

How to use ExecuteReader, you can check here : 如何使用ExecuteReader,可以在这里检查:

static void HasRows(SqlConnection connection)
{
    using (connection)
    {
        SqlCommand command = new SqlCommand(
          "SELECT CategoryID, CategoryName FROM Categories;",
          connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}
conn1.Open();
string query = "select feedurl from [dbo].[feeds]";
DataSet DS = new DataSet();
SqlDataAdapter adapt = new SqlDataAdapter(query,conn1);
adapt.Fill(DS);
if (DS != null)
{
     if (DS.Tables[0].rows.Count > 0 )
    {
        foreach(DataRow DR in DS.Tables[0].Rows)
        {
            string temp = DR['columnname'];
        }
    }
{

Try this: 尝试这个:

//method to make this code reusable
//the returned data set is accessible even if the underlying connection is closed
//NB: that means data's held in memory; so beware of your resource usage
    public DataSet ExecuteSQLToDataSet(string ssConnectionString, string query, string name)
    {
        DataSet ds = new DataSet("Tables");
        using (SqlConnection conn1 = new SqlConnection(ssConnectionString))
        {
            conn1.Open();
            SqlDataAdapter sda = new SqlDataAdapter(query, objConn);
            sda.FillSchema(ds, SchemaType.Source, name);
            sda.Fill(ds, name);
        } //using statement will close and dispose the connection for you
        return ds;
    }


//example usage

    DataSet ds = ExecuteSQLToDataSet(ssConnectionString, "SELECT FeedURL FROM [dbo].[Feeds]", "Feeds"); //nb: name doesn't have to match table name; you can call it what you like; naming is useful if you wanted to add other result sets to the same data set

    //DataTable tblFeeds = ds.Tables["Feeds"]; //if you want to access the above query by name

    foreach (DataTable tbl in ds.Tables)
    {
        foreach (DataRow dr in tbl.Rows) //tblFeeds.Rows if you did that instead of looping through all tables
        {
            //Console.WriteLine(dr["FeedURL"].ToString()); //you can specify a named column
            Console.WriteLine(dr[0].ToString()); //or just use the index
        }
    }
    Console.WriteLine("Done");
    Console.ReadLine();

More Detail: http://support.microsoft.com/kb/314145 详细信息: http : //support.microsoft.com/kb/314145

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM