简体   繁体   中英

Close OracleConnection after ExecuteReader

This is my current pattern

private void ReadData(string connString, string cmdString)
{
    using (OracleConnection conn = new OracleConnection(connString))
    {
        conn.Open();
        OracleCommand cmd = new OracleCommand(cmdString, conn);
        OracleDataReader reader = cmd.ExecuteReader();
        //some long operation using reader
    }
}

In the above case, the connection remains open while the long operation is going on. Is there a way I could close the connection but still preserve the reader. Is that going to be advantageous?

If by long operations you mean to say that you need to do extra operations on the database (like update/insert/delete), then you cannot close the connection.

If you want to read the data and do some calculation based on it, then you should modify you pattern to: 1. read all the data, 2. close the connection, 3. do long operation on the data.

using System;
using System.Collections.Generic;
using Oracle.DataAccess.Client;

namespace Utils
{
    class Test
    {
        private class Class
        {
            public string FirstProperty { get; set; }
            public string SecondProperty { get; set; }
        }

        private void ReadData(string connString, string cmdString)
        {
            List<Class> data = new List<Class>();
            using (OracleConnection conn = new OracleConnection() { ConnectionString = connString })
            using (OracleCommand objCmd = new OracleCommand()
            {
                Connection = conn,
                CommandText = cmdString
            })
            {
                try
                {
                    conn.Open();
                }
                catch (OracleException)
                {
                    OracleConnection.ClearPool(conn);
                    conn.Open();
                }
                using (OracleDataReader dataReader = objCmd.ExecuteReader())
                {
                    while (dataReader.Read())
                        data.Add(new Class()
                        {
                            FirstProperty = dataReader.GetString(0),
                            SecondProperty = dataReader.GetString(1)
                        });
                }
                conn.Close();
            }
            //some long operation using data
        }
    }
}

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