简体   繁体   中英

Closing SQLite with C# in Unity

I'm making an app for Android with Unity now.

But I have very very basic questions about SQLite because I've never used database yet.

dbcmd.CommandText = "some select command here";

IDataReader reader = dbcmd.ExecuteReader();

// some jobs with the reader..


dbcmd.CommandText = "another select command here";

reader = dbcmd.ExecuteReader();

// some jobs with the reader..


reader.Close();
dbcmd.Dispose();
dbconn.Close();

reader = null;
dbcmd = null;
dbconn = null;

I need to call ExecuteReader() method several times like that.

Here are my questions.

  1. Do I have to close the reader before I call ExecuteReader() method AGAIN ?

  2. Do I have to assign null to the variables after closing the reader and database like above?

Thanks in advance!

  1. Read about using statement - it is the construct designed specially for such use cases.
  2. Yes, the second call to ExecuteReader() returns you a brand new reader object, that must be closed/disposed too, when you don't need it anymore. It's a question about variables and object references that they store.
  3. It is a good practice in many cases (especially if reader and dbcmd is the instance fields), because you mark that it is no reference to valid (non-disposed) object in the variable. But this is not critical, if this variable is, for example, local to the current function.

Closing it depends if you need to keep it open, and if that instance of the reader and connection will persist to your next call. The easiest way to find out is to run it and see if you get an error. I usually just open connection, create the reader, read, then close connection, dispose of the reader each time. There are no real performance issues here unless you are just madly hammering the database super quickly. Since its SQLite, it would be local and pretty snappy, so no real issue in latency if you open and close rapidly.

As far as setting things to null, no you don't need to. It doesn't hurt to do it though. That will all get collected in GC and dumped anyhow.

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