简体   繁体   中英

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.

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. You would need to create a DataReader , and then loop through the results using command1.ExecuteReader()

You can just use ExecuteReader for your problem. In this example that I took from MSDN is consuming the connection with using statement because SqlConnection class has some unmanaged resources. If you have more questions about using and Finalizers also check here .

How to use ExecuteReader, you can check here :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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