jeudi 28 mai 2015

Static "Connection" in JDBC: Can connections get mixed up?

Below is my code.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Yohan
 */
public abstract class DBMaster 
{
    public static Connection con;

 /**
 *
 * Initializes the connection
 */
    public void createConnection() 
    {   
        try
        {           
            Class.forName("com.mysql.jdbc.Driver");

            try
            {               
              con=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB","root","");
            } 
            catch (SQLException ex)
            {
                ex.printStackTrace();
            }            
        } 
        catch (ClassNotFoundException ex)
        {
             ex.printStackTrace();
        }
    }


    public void closeConnection() 
    {

    }

 /**
 *
 * check if the connection is successful or not
 */

    public void checkConnection() 
    {            
            ResultSet resultset=null;
            String cmd="select * from user";    

            try
            {
                Statement statement=con.createStatement();
                resultset=statement.executeQuery(cmd);

            }
            catch(SQLException ex)
            {
                if(ex.getLocalizedMessage().equals("No operations allowed after connection closed."))
                {
                    createConnection();
                    System.out.println("System Loaded");
                }
            }
            catch(NullPointerException ne)
            {
                createConnection();
                System.out.println("System Loaded");
            }

    }
}

As you can see, this is a super class, where the subclasses will extend. The sub classes will use the static variable con after extending. sub classes will contain the database code.

I have implemented this class in web applications, where JSP and Sevlet are being used. Now my question is, can JDBC connection "ever" be shared in web applications? The Connection is static here, so can "connection1" get mixed up with "connection2" and and do some nasty work?

For an example, in this web application, "connection1" is deleting a record while "connection2" is updating a record. "connection1" belongs to "web application user 1" and "connection2" belongs to "web application user 2". Instead of deleting the record, can connection 1 mix with connection 2 and perform the "update"?

As far as I know, this code allows very speed database access without issues upto now(tested only with one web application user), but I am willing to learn more.




Aucun commentaire:

Enregistrer un commentaire