First i show you the code then asked few questions. i have a class database connectivity like this (please ignore syntax error if any)
class DatabaseConnection {
private static Connection connection = null;
private static String driverName="";
private static String userName="";
private static String passwrod="";
private static String url="";
private DatabaseConnection() { }
public static void createConnection() {
if ( connection == null ) {
// read database credentials from xml file and set values of driverName, userName, passowrd and url
//create connection with database and set store this connection in connection object created a class level.
}
}
public static void closeConnection1() throws Exception{
if ( connection != null ) {
connection.close();
connection == null
}
}
public static void closeConnection2() throws Exception{
if ( connection != null ) {
connection.close();
}
}
public void insertData(Object data) {
// insetData in database
}
}
I want to know which close connection is more optimize in database connection. Lets suppose I have test class like this
class Test {
public static void main(String args[]) {
DatabaseConnection.createConnection();
DatabaseConnection.insertData(data);
DatabaseConnection.closeConnection2(); // we call also called close connection method within the insertData method after inserting the data
}
}
After creating database connection i insert data in database and then close the connection using closeConnection2 method. in this way connection has been close so if i want to insert some more method then i have to recreate connection with the database but i can't do this because connection object is not null and createConnection didn't execute the code inside the if statement. Now if I called closeConnection1 method for closing connection then in doing this i have to parse xml file again for credential which is not a optimize solution. can you tell me which method is good and if both are worse then please tell me more efficient way for creating and closing database connection.
I see two major problems with this:
The fact that everything (including the Connection object) is static means that you can't ever use this class from more than one thread at once.
parsing the configuration data and opening the connection are separate concerns and should not be mixed. At least move them into separate methods, the configuration could probably even go in another class.
The second thing alone will avoid having to parse the connection information multiple times.
An even better approach would be to use a DataSource instead of opening the connections each time. And then use a DataSource that's actually a connection pool!
Related
I have created a hbase scan method, but I am creating and closing the Connection inside the method itself. Could anyone suggest how to create a common connection, so that I can use the connection for a put, etc
I was not sure when to close the connection.
public class HBaseConnection {
private static Connection connection;
public void scanHBase(String tableName, byte[] startRow, byte[] stopRow) throws IOException {
connection = ConnectionFactory.createConnection(hBaseConn);
Table tableRef = connection.getTable(tableName);
Scan scan = new Scan(startRow, stopRow);
ResultScanner scanner = tableRef.getScanner(scan);
System.out.println("Starting scan");
for (Result res : scanner) {
//do something
}
scanner.close();
tableRef.close();
connection.close();
}
}
The Connection object that I created inside the scanHBase() I need to create it outside as well as close it outside. Is there a possibility for this. I am new to Java and new to Hbase as
You can define the shared connection as static and instantiate it in a static block.
You can create a connection somewhere else (like in a connection factory) and pass it as an argument to each constructor (or getting from the factory inside the constructor).
The other (not really good) solution is to define a static connection and in the constructor check if it is null, create the object, if not just use it
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a java based application using NetBeans. My app opens with a window with asks the user to enter their credentials and based on data entered, a connection is established between the app and my MySQL client (I'm using JDBC for this purpose).
My issue: I want the connection object (which is declared and initialized after checking the credentials of the user) to be available for use in all my form. Previously, i have being doing this by passing the connection object from one form to another. But i don't want to do that! I want once this connection object is declared, it's made available to all the forms in the app.
I want the connection object (...) to be available for use in all my form
You should not have an open connection while your application lives. Instead, use a database connection pool of 1 or 2 connections that will be available for all the application and add a shutdown hook to close this data source when the application finishes. The connection pool will take care to maintain the connections alive and use low resources for it.
For example: your user opens the application and enters its credentials, then leaves the room because he/she has to do some paperwork and takes 30 mins, then goes back to the pc and try to use an option. If using a static Connection con object, you manually opened a physical connection to the database and you're in charge to control the connectivity for all these 30 minutes, and if you don't do any action in that time then probably the physical connection was closed by the database engine. If using a connection pool, this will take care of opening/closing physical connections and maintaining them in sleep state so your connection won't be lost.
Note that your Connection object and related resources (PreparedStatement, ResultSet, etc). should be in the narrowest possible scope.
Here's a minimal example of doing this using BoneCP as database connection pool.
public class ConnectionProvider {
private static DataSource dataSource;
private static boolean initialized = false;
public static void init(Map<String, String> conf) {
if (!initialized) {
//synchronization to avoid multiple threads accesing to this part of the method
//at the "same time"
synchronized(DataSourceProvider.class) {
//double validation in case of multi threaded applications
if (!initialized) {
//you may add more validations here
//in case you want to use another datasource provider
//like C3PO, just change this part of the code
BoneCPDataSource bds = new BoneCPDataSource();
bds.setDriverClass(conf.get("driver"));
bds.setJdbcUrl(conf.get("url"));
bds.setUsername(conf.get("user"));
bds.setPassword(conf.get("password"));
//this should be obtained as configuration parameter
bds.setMaxConnectionsPerPartition(2);
//you can add more BoneCP specific database configurations
dataSource = bds;
initialized = true;
}
}
}
}
public static Connection getConnection() {
if (dataSource == null) {
//this should be a custom exception in your app
throw new RuntimeException("Data Source was not initialized.");
}
return dataSource.getConnection();
}
}
And the client (once you have called the init method and provided the database configurations). I'm avoiding exception handling for brevity:
public class SomeDao {
private Connection con;
//using Dependency Injection by composition for DAO classes with connection
public SomeDao(Connection con) {
this.con = con;
}
public SomeEntity getSomeEntity(int id) {
String sql = "SELECT id, col1, col2 FROM someEntity WHERE id = ?";
//PreparedStatement and ResultSet go on the narrowest possible scope
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
SomeEntity someEntity = new SomeEntity();
if (rs.hasNext()) {
someEntity.setId(rs.getInt("id");
//similar for other columns...
}
//don't forget to close the resources after its usage
return someEntity;
}
}
public class SomeService {
public SomeEntity getSomeEntity(int id) {
//retrieving the connection at this level
//a service may access to several daos
Connection con = ConnectionProvider.getConnection();
//performing the operations against DAO layer
SomeDao someDao = new SomeDao(con);
SomeEntity someEntity = someDao.getSomeEntity(id);
//closing the connection. This is A MUST
//here the connection pool won't close the physical connection
//instead put it to sleep
con.close();
//return the proper data at a single point of the method
return someEntity;
}
}
Don't use the same Connection in your application! But what you want to achieve could be done using static variable. For example, add the following code to any of your classes, or create a new class for it:
private static Connection con = null;
public static Connection getConnection (String url)
{
if (con == null)
con = DriverManager.getConnection(url);
return con;
}
Then, call MyClass.getConnection("jdbc:mysql://localhost:3306/") or whatever the connection string is, and it will return one Connection that you could use for all classes.
For university, it is my excercise to develop a multiplayer game with Java. The communication between the clients shall not be handled with sockets or the like, but with the help of a MySQL database where the clients are adding their steps in the game. Because it is a game of dice, not a lot of queries are needed. (approximiately 30 queries per gaming session are needed).
I never used MySQL in connection with Java before, so this maybe is a beginner's fault. But actually, I often get an exception during the execution of my java project.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: User my_username already has more than 'max_user_connections' active connections
My queries are executed in a DatabaseHelper.java class. The results are returned and evaluated in another class of the project. Since I use an MVC pattern, I evaluate the results in a controller or model class.
This for example is one of my quers in the DatabaseHelper.java class. The other queries are similar:
private static Connection conn;
private Connection getConn() {
return conn;
}
public void db_connect() throws ClassNotFoundException, SQLException{
// JDBC Klassen laden
Class.forName(dbClassName);
// Verbindungsversuch auf 5 Sekunden setzen
DriverManager.setLoginTimeout(5);
this.setConn(DriverManager.getConnection(CONNECTION,p)); // p contains the username and the database
}
public void db_close(){
try {
this.getConn().close();
} catch (SQLException e) {
if(GLOBALVARS.DEBUG)
e.printStackTrace();
}
}
public String[] query_myHighscores(int gameid, PlayerModel p) throws SQLException{
List<String> rowValues = new ArrayList<String>();
PreparedStatement stmnt;
if(gameid == GLOBALVARS.DRAGRACE)
stmnt = this.getConn().prepareStatement("SELECT score FROM highscore WHERE gid = ? and pname = ? ORDER BY score ASC LIMIT 0,3");
else
stmnt = this.getConn().prepareStatement("SELECT score FROM highscore WHERE gid = ? and pname = ? ORDER BY score DESC LIMIT 0,3");
stmnt.setInt(1, gameid);
stmnt.setString(2, p.getUname());
ResultSet rs = stmnt.executeQuery();
rs.beforeFirst();
while(rs.next()){
rowValues.add(rs.getString(1));
}
stmnt.close();
rs.close();
return (String[])rowValues.toArray(new String[rowValues.size()]);
}
The CONNECTION string is a string which looks like jdbc:mysql://my_server/my_database
In the HighscoreGUI.java class, I request the data like this:
private void actualizeHighscores(){
DatabaseHelper db = new DatabaseHelper();
try{
db.db_connect();
String[] myScoreDragrace = db.query_myHighscores(GLOBALVARS.GAME1); // id of the game as parameter
// using the string
} finally {
db.db_close();
}
So I tried:
Closing the statement and the ResultSet after each query
Used db_close() to close the connection to the dabase in the finally-block
Never returning a ResultSet (found out this may become a performance leak)
The stacktrace leads in the DatabaseHelper.java class to the line
this.setConn(DriverManager.getConnection(CONNECTION,p));
But I cannot find my mistake why I still get this exception.
I cannot change every settings for the database since this is a shared host. So I'd prefer a solution on Java side.
The problem is that you exceed your allowed set of connections to that database. Most likely this limit is exactly or very close to "1". So as soon as you request your second connection your program crashes.
You can solve this by using a connection pooling system like commons-dbcp.
That is the recommended way of doing it and the other solution below is only if you may not use external resources.
If you are prohibited in the external code that you might use with your solution you can do this:
Create a "Database" class. This class and only this class ever connects to the DB and it does so only once per program run. You set it up, it connects to the database and then all the queries are created and run through this class, in Java we call this construct a "singleton". It usually has a private constructor and a public static method that returns the one and only instance of itself. You keep this connection up through the entire livetime of your program and only reactivate it if it gets stall. Basically you implement a "Connection Pool" for the specific case of the pool size "1".
public class Database {
private static final Database INSTANCE = new Database();
private Database() {}
public static Database getInstance() {
return INSTANCE;
}
// add your methods here.
}
When the program terminates, close the Connection (using a shutdown hook).
I am developing a web application using JSP and Servlets.(Database: Oracle10, Container: Glassfish).
I have developed A Class for creating connection.
(Conn.java):
public class Conn
{
private Connection con = null;
public Connection getCon()
{
String home = System.getProperty("user.home");
home = home+"\\dbFile.properties";
//Read properties of Connection String from that file and Create Connection
return con;
}
}
Then I have a 4 other classes for SELECT, INSERT, UPDATE, DELETE transactions which are using above Conn.java class for getting connection:
(Select.java)
public class Select
{
private Conn connection = new Conn();
private Connection con = null;
private PreparedStatement pstmt = null;
private ResultSet rs=null;
public String[][] selectData(String query)
{
String[][] data=null;
if(con==null)
{
con = connection.getCon();
}
//execute query put data in two dimensional array and then return it
return data;
}
}
INSERT, UPDATE and DELETE are coded similar way as above Select.java is coded.
So in all servlets I am just using those 4(SELECT, INSERT, UPDATE, DELETE) classes, passing query to them and getting the result.
Sample Servlet
public class SampleServ extends HttpServlet
{
Select select = new Select();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String data[][];
data = select.selectData(QUERY_GOES_HERE);
//AND OTHER CODE
}
}
It works perfectly, but now our requirement is to change Database String after user is login. So I want to pass the User specific property file name to the Conn.java class. So for that I am storing the property file name in cookie.
I have think one way of doing this:
Get the cookie value in all servlets
Pass the cookie value to the selectData() method of Select.java class And from that class
pass the cookie value to the getConn() method of Conn.java class
So I want know if there is any better way to pass this Connection String file name to Conn.java class?
Thanks in advance.
HttpSession is where user info should be stored (with some concerns).
In your case, where you seem to have many different web applications, each of them will have a different session, and you will need to update all of them.
I prefer another approach (and this is a personal opinion, which can be discussed) which is based in the ThreadLocal class.
You can write a servlet filter, that will
read the cookie value
store it in a ThreadLocal
after the filter.doFilter method, you will have to clean it (This is extremely important, so you don't the have the chance of mixing sessions), just put the clean method in a finally block so it gets executed whatever happens.
The main advantage of this approach is that you may not have access to the HttpSession or HttpServletRequest, and you will still be able to get the value in the ThreadLocal.
An example of a ThreadLocal container you can use is this one :
public class ThreadLocalContainer {
private static ThreadLocal<String> userId=new ThreadLocal<String>();
public static String getUserId(){
return userId.get();
}
public static void setUserId(String uid){
userId.set(uid);
}
public static void resetUserId(){
userId.remove();
}
}
then you will be able to access the userId just by calling ThreadLocalContainer.getUserId() everywhere in your code, even if you don¡t have access to the http context.
Make sure you define the servlet filter in all your webapps, so the userId gets properly set.
I am in the process of designing a simple Java application which deals with insert/delete/update of records in a MySQL database using JDBC. I have a class Member which deals with the member's details.
class Member {
... // Private Members
... // Accessors
}
..and I have a handler to deal with the member records
class MemberHandler {
public MemberHandler(){...}
public void addMember(Member mem){...}
public void removeMember(Member mem){...}
public Member[] getMembers(){...}
}
All I am worried about is the method in which I establish connection to the database and disconnect. I can do it in two ways -
Method 1:
I can have a member in MemberHandler Connection conn, establish connection while instantiating the class and close the connection when the object is no more needed. Here I would have a connection per object and I need not establish a connection whenever I need to do any database related activity. In this case, the disadvantage seems to be - when there is a loss in network connection, conn could become invalid.
class MemberHandler {
private java.sql.Connection conn;
... // Other members
private void createConnection(){/*creates the connection*/}
private void closeConnection(){conn.close(); /*called when conn is no more needed*/}
}
Method 2:
I can establish a connection when needed and close it when I am done with the activity. Disadvantage: everytime, I need to establish a connection and close it. For eg.,
...
...
private void addMember() {
//establish connection
//update database
//close connection
}
...
...
Which of these two ways seems to be better? Or is there a third better way?
Thanks!
I would suggest you to go for connection-pooling
c3po