함수에서 OleDb.OleDbDataReader 개체를 반환 할 수 있습니까?
그렇다면 어떻게 하시겠습니까?
내 현재 코드는 데이터 판독기 개체를 반환하지만 해당 개체를 읽으려고하면 다음과 같은 오류가 발생합니다. System.InvalidOperationException: 'Invalid attempt to call Read when reader is closed.'
내 코드 :
OleDbDataReader queryData = sendQueryReturnData("SELECT * FROM users WHERE username = ?;", Parameters);
while (queryData.Read()) //error on this line
{
//stuff
}
queryData
범위 내에서 유지하는 한 가지 방법 은 다음과 같이 IDisposable
유형 의 필드를 만들고 다른 메서드가 닫지 않도록하는 것입니다.
using System;
using System.Data.OleDb;
namespace TwitterSeachTest
{
public class MyDataClass : IDisposable
{
OleDbDataReader queryData;
OleDbCommand command;
OleDbConnection conn;
public object[] Parameters { get; set; } = new object[0];
public void DoReadData()
{
sendQueryReturnData("SELECT * FROM users WHERE username = ?;", Parameters);
while (queryData.Read()) //error on this line
{
//stuff
}
}
private void sendQueryReturnData(string queryString, object parameters)
{
this.conn = new OleDbConnection("connectionstring");
this.command = new OleDbCommand(queryString, conn);
conn.Open();
this.queryData = command.ExecuteReader();
// your code
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.queryData?.Close();
this.command?.Dispose();
this.conn?.Close();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MyDataClass()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
코드를 입력했는데 DoReadData
차이점 queryData
은 이제 지역 변수 대신 필드라는 것입니다.
에 대한 몇 가지 예제 코드도 추가했습니다 sendQueryReturnData
. 공지 사항은이 결과를 할당하는 command.ExecuteReader
받는 사람 queryData
필드. using
여기서 사용하지 마십시오 .
마지막으로 IDispose
. 이렇게하면이 클래스를 사용하는 사람은 이제 using
문이나 호출을 사용해야합니다 Dispose
.
즉, 일반적으로 데이터베이스에서 데이터를 읽고 작업이 완료되는 즉시 DB 개체를 닫거나 폐기하는 것이 더 쉽습니다. 대신 데이터를 나타내는 DTO를 만들고 a를 채우고 반환 한 List<MyDataDto>
다음 리소스를 닫거나 폐기합니다. 이렇게하면 해당 리소스를 해제 할 책임이있는시기와 사람의 모호성이 줄어 듭니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다