When is it recommended to open and close the database?

I am developing an application using a database, but I do not know when it is useful to close it?

It is recommended to close every time, or should I stay open until the application is closed?

thanks

+4
source share
8 answers

You can use ContentProvider . It also simplifies the processing of databases and data from many activities and fragments. You also take minimal effort to handle the db connection

+2
source

In the main action, do:

 public static DataBaseConect db=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db=new DataBaseConect(this);} @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); db.close(); } 
0
source

Close the database when your activity is destroyed.

 @Override protected void onDestroy() { super.onDestroy(); //close db in here. } 
0
source

The recommended way is to use a connection pool, for example Apache commons-dbcp http://commons.apache.org/proper/commons-dbcp/ and close ResultSet, Statement and Connection immediately after use.

0
source

I am not sure about the architecture of your code. Connections basically open at the DAO level, and the code to close the connection should be in the finally block.

0
source

Connecting to the database takes a finite time. This is insignificant when connected via a domain socket or named pipe, but it can be much more if it is connected via a network connection or, even worse, an open Internet. Leave it connected to life at least. And in the end, you should always close it, from time to time it will be implicitly executed when the program terminates, but it is good practice to keep a check.

0
source

The general consensus is that you close the database connection after you have finished using it.

For example, it may be after using the connection only once at startup, you should close it after this initial use.

You might want to use the database connection again, but in this case you should leave it open.

0
source

It will always be useful to open and close the connection for each operation of the request ... sometimes the user may need time to send the request and save the connection to the database for the log, time is not recommended. In java, you can use the "Finally" block to call the method to close the connection. In C u, you can use a destructor to call the method to close the connection ... or explicitly when you execute the query

0
source

Source: https://habr.com/ru/post/1499327/


All Articles