I am using android studio to make a calender application. I made a database to save an event.I was able to open the event as long as the Android Virtual Device was running but when I closed it and opened it again I would not open the event again. Is it possible that the database remains as long as the AVD is running?
Well I can see in your snippet that you are doing your query and your data manipulation in the same class, if you'd had separated the responsibility away then the life of opening and closing a connection could have been easier.
You should have created a DatabaseFactory which sets up the connection to the database. Have simple methods like openConnection(string connectionString) Close() and query(string sql, string[] param).
Another class called DatabaseConsumer should basically open a connection, use the query, return the data however you want (ResultSet?), then close the connection after.
But to answer your question in terms of your design, you can just close the connection after your finished your while statement (res.moveToNext). Something like myDB.closeConnection() ?
edit : Implications of not closing a connection can leave the server holding that connection, some config value will say how many open connections your DB can handle. After a while the database will not allow the connection and give you an SQLServerException, boohoo.
Related
i have an application that receive Id from Web service and store it into database if received Id for any reason like connection failed could not store in database i want to know what id was.
is there any way to do it or is there any sample code?
i want use java language.
Use triggers. If you use triggers than you can revoke the transactions in sql.
Do you want a way to make sure that you don't lose the ids even if there is failure in the connection?
If so, why don't you save the last Id you receive in your code that way, you can check if there are more IDs after the last one in case of an outage, Or in your code you can make sure that the web service is reachable, and if it isn't store the IDs till the connection is restored.
I have created a database application using java swing. My program retrieves data from the database whenever I call the find class. The find class simply creates a statement, get the current database connection, then execute the statement. The returned values from the database will be placed on a ResultSet then will be displayed on a jTable. The problem is this:
I opened the find class, the result was displayed. Then I go to SQLyog or HeidiSQL (applications to manipulate the database), edit the values which was displayed on my program, then save. I went back to my program, close the find class then reopen it, I still get the previous data, not the edited one. Please help. Updates must be displayed once the find class is open. The only way for me to get the updated data is to close my entire program then reopen it, which I dont want to do.
EDIT:
This is what I tried. Basically, once my program creates a connection to the database the first time, I save it to another class which makes the connection always open(I assume). So whenever I want to create a query, I'll just call the class to get the connection. What I did now is, after executing the query from the find class, I close the connection with the .close() function. It works, but do I really need to do close the connection every time? Again this is just a desktop application, not a web program.
I think you're having a transaction isolation issue. Some drivers start an implicit transaction when it grabs the connection so you're seeing a snapshot of the database at that time. You probably want a READ COMMITTED level which should show the database with all committed transactions applied.
Looks like either you have not commit the edit or you need to refresh data by refreshing query.
I have a web application that needs a database back-end.
My back-end is really small (max 4 tables) and the SQL operations are not that much.
So I decided that some robust ORM solution is like hitting a moschito with a hummer and I am going just to do a little DAO pattern so that the code is more clean (instead of hitting the db directly with sql commands).
So far it works but I am not sure that I haven't stepped into a pittfall without knowing.
I use Tomcat's connection pool and I expect concurrent access to the database.
My question is related to concurrency and the use of the java sql objects.
Example:
I do the following:
do a query
get a result set and use that to build an object (dto)
building this object I do a new sql query (using the same connection
and having the previous resultset open)
Is this correct/safe?
Also can I reuse the same connection in a re-entrant manner?
I assume it is no problem to use it via multiple threads right?
Generally any tips/guide to get in the right track is welcome
Regarding the connections, as long as you use the connection pool you are guaranteeing that each thread takes its own connection, so from that point of wiew, there is no problem in your approach in a multithreaded environment (you can check Is java.sql.Connection thread safe?).
With respect to the ResultSet and the second query you are performing, you must take into account that a ResultSet maintains a cursor pointing to its current row of data. So the key point in your question is if you are using the same "SELECT statement", because of in that case, you could get the same cursor attributes and some problems may arise.
Check ResultSet's javadoc, especially this sentence:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
and How can I avoid ResultSet is closed exception in Java?.
My Java application needs to hold cursor to Oracle DB for some time. During it other DB statements have to be made. Does this require separate DB connections or same (cursor's one) can be used?
Thanks.
The only restriction is that a single statement can only have a single ResultSet at a given time. Note that a statement can produce multiple ResultSets but you have to access them sequentially (using getNextResult())
To be able to have multiple open ResultSets/Cursors you need multiple java.sql.Statement objects.
A single connection can only have a single active (i.e. running) statement. So if you have need multiple open cursors (ResultSets) you need to run them sequentially (one after the other) each with their own Statement object.
Oracle has no problem with what the MSSQL folks call MARS (Multiple active result sets).
You can see this kind of thing in a lot of PL/SQL code, and for that matter PL/SQL is "just" a client to the SQL engine as is your Java code:
for a in (select field1, field2 from table1) loop
for b in (select * from table2 where SomeField = a.Field1) loop
...
end loop;
end loop;
Don't take my word for it, though. You can create a nested loop like this yourself in Java.
Of course you can hold multiple open cursors while you're issuing other queries on the same connection. However, it's not possible to issue other queries or statements while the first cursor is beeing opened. That's because only one request can be active (i.e. beeing executed) in an Oracle session at any point in time.
You can use the concept of database pooling.
Click Here
It provides a pool of database connections so whenever needed you can get a database connection from pool.
It is also memory optimized since database connection and closing is a heavy process.
I've ran through several examples over the web, and found that every single time I need something from the DB, I should write the following code:
try
{
// Step 1: Load the JDBC driver.
Class.forName("mysql_driver_name");
// Step 2: Establish the connection to the database.
String url = "jdbc:string_to_mysql_server";
Connection conn = DriverManager.getConnection(url,"user1","password");
// fetch from the DB ...
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
It's very annoying to put up this code every time I want something from the DB, so the question is - is there a way to only once connect entirely all my app to the DB somehow at the very start point, avoiding copy-pasting mentioned code, and then be able to do everything I want with DB?
I've quickly looked through NetBeans's Project menu, but didn't find any clue on how to configurate a persistent connection to a selected DB.
If it's important, i'm writing a purely desktop app, i.e. using Java SE. Also, it's worth mentioning that I'm a kinda beginner in Java.
There are many connection pool options to choose from, I would suggest that you try Apache Common Db Connection Pool http://commons.apache.org/dbcp/.
The connection pool idea is probably the best overal solution. However there is a simpler one in ypur case.
In your code conn goes out of scope in the method itwas created. There is no need to do that. You can create a method that includes all your code up to an including the line that assigns to conn. Then pass that conn variable to other parts of the program and use that for db work.
You can follow this Method of Establishing the Conenction
Create a Singleton class, which helps you to create a connection
In your DAO or any helper Class, Call this Single instance, which has a connection
Once you get the Conenction, write the operations that you want to perform on the database.
Close the connection, that will do to fullfill your connection.
This will avoid the code, what you have written in your query.
and this style will increases the readability and reduce the maintainability.
If you want any sample code let me know, I can provide you that