Solved

JAVA: How can I set up a JDBC Connection Globally so the connection can be used from anywhere in the program?

Posted on 2007-11-17
4
322 Views
Last Modified: 2013-12-14
Well I'm kinda new to Java. I have some background from college but not advances like the code I'm trying to write.

I am making a Java Application that connects to a Oracle 9i Database.
I started off by creating a login page. Which then I create a object to that method in another Class in another Java file which establish the connection to the database to determine if the connection can be established. But I'd like to make it in a way that I can use the JDBC built in functions like closing the db connection, sending sql using that same connection, getting results using that open connection, without having to create multiple connections and establish one every time. I expect to have other java classes that will use this connection to bring results back into a JTable and even a JTree.

I don't think this information would be helpful, but I am using Netbeans 5.5.1 and Java 1.6.0.03
/*
 * login.java
 *
 * Created on November 15, 2007, 10:25 PM
 */
 
package com.user;
import com.app.db.*;
import java.awt.Color;
import java.awt.LayoutManager;
import oracle.jdbc.util.Login;
/**
 *
 * @author  
 */
public class login extends javax.swing.JFrame {
private static final long serialVersionUID = -3088001842L;
 
    /** Creates new form login */
    public login() {
        initComponents();
        failedpassword.setVisible(false);
        failedusername.setVisible(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        usernamelb = new javax.swing.JLabel();
        passwordlb = new javax.swing.JLabel();
        serverlb = new javax.swing.JLabel();
        usernametxt = new javax.swing.JTextField();
        passwordtxt = new javax.swing.JPasswordField();
        serverName = new javax.swing.JComboBox();
        loginbtn = new javax.swing.JButton();
        exitbtn = new javax.swing.JButton();
        failedusername = new javax.swing.JLabel();
        failedpassword = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
 
        setTitle("ILog Login");
        setLocationByPlatform(true);
        setResizable(false);
        usernamelb.setText("Username:");
 
        passwordlb.setText("Password:");
 
        serverlb.setText("Server:");
 
        passwordtxt.setColumns(10);
 
        serverName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ILOG" }));
 
        loginbtn.setText("Login");
        loginbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginbtnActionPerformed(evt);
            }
        });
 
        exitbtn.setText("Exit");
        exitbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitbtnActionPerformed(evt);
            }
        });
 
        failedusername.setFont(new java.awt.Font("Tahoma", 0, 12));
        failedusername.setForeground(java.awt.Color.red);
        failedusername.setText("*");
 
        failedpassword.setFont(new java.awt.Font("Tahoma", 0, 12));
        failedpassword.setForeground(java.awt.Color.red);
        failedpassword.setText("*");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(loginbtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(exitbtn)
                .addContainerGap(86, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(usernamelb)
                    .addComponent(passwordlb)
                    .addComponent(serverlb))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(serverName, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(usernametxt, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordtxt, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(failedpassword)
                    .addComponent(failedusername))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(25, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernamelb)
                    .addComponent(usernametxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(failedusername))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordlb)
                    .addComponent(passwordtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(failedpassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serverlb))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginbtn)
                    .addComponent(exitbtn))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>                        
 
    private void loginbtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        failedpassword.setVisible(false);
        failedusername.setVisible(false);
        
        usernamelb.setForeground(Color.BLACK);
        passwordlb.setForeground(Color.BLACK);
        
        String v_username = usernametxt.getText();
        char[] Getpassword = passwordtxt.getPassword();
        String v_password = convertPassword(Getpassword);
        
        if ( ( v_username.length() == 0 ) || ( v_username.contains(" ") ) ) {
            failedusername.setVisible(true);
            usernamelb.setForeground(Color.RED);
            if ( ( v_password.length() == 0 ) || ( v_password.contains(" ") ) ) {
                failedpassword.setVisible(true);
                passwordlb.setForeground(Color.RED);
            }
        } else if ( ( v_password.length() == 0 ) || ( v_password.contains(" ") ) ) {
            failedpassword.setVisible(true);
            passwordlb.setForeground(Color.RED);
            if ( (counter >= 3) ){
                System.exit(0);   
            }
                counter = counter + 1;
        } else {
            dbConnect run = new dbConnect();
            // String v_servername = (String) serverName.getSelectedItem();
            int v_servername = serverName.getSelectedIndex();
            run.startConnect(v_username, v_password, v_servername);
        }
    }                                        
    
    private void exitbtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        System.exit(0);
    }                                       
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new login().setVisible(true); } } );        
    }
    
     public static String convertPassword(char[] userPassword) {
        // Declare variables
        String strRet = new String("");
            // Go through each character
            for (int i = 0; i < userPassword.length; i++)
            {
                strRet += userPassword[i];
            }
        return strRet;
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton exitbtn;
    private javax.swing.JLabel failedpassword;
    private javax.swing.JLabel failedusername;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton loginbtn;
    private javax.swing.JLabel passwordlb;
    private javax.swing.JPasswordField passwordtxt;
    private javax.swing.JComboBox serverName;
    private javax.swing.JLabel serverlb;
    private javax.swing.JLabel usernamelb;
    private javax.swing.JTextField usernametxt;
    // End of variables declaration                   
    int counter = 0;
}
 
 
 
/*
 * dbConnect.java
 *
 * Created on November 16, 2007, 3:33 PM
 *
 * @author cj58096
 */
 
package com.app.db;
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.swing.JOptionPane;
 
public class dbConnect {
    /** Creates a new instance of dbConnect */    
    public void startConnect(String loginUsername, String loginPassword, int v_serverno ) {
 
            String serverName = null;
            String server = null;
 
            String sResult = "Worked";
            Connection connection = null;            
            
            switch ( v_serverno ){
                case 0: serverName = " "; server = "P"; break;
                case 1: serverName = " "; server = "IM"; break; 
                case 2: serverName = " "; server = "OS"; break; 
                case 3: serverName = " "; server = "Q"; break; 
                case 4: serverName = " "; server = "IMQ"; break; 
                case 5: serverName = " "; server = "OSQ"; break; 
                case 6: serverName = " "; server = "T"; break; 
                case 7: serverName = " "; server = "IT"; break; 
                case 8: serverName = " "; server = "OT"; break; 
                case 9: serverName = "192.168.1.4"; server = "World"; break;
            }
    try
            {
            // Load the JDBC driver
              String driverName = "oracle.jdbc.driver.OracleDriver";
              Class.forName(driverName);
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
 
            // Create a connection to the database
              String portNumber = "1521";
              String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + server;
              connection = DriverManager.getConnection(url, loginUsername, loginPassword);
              
          }
            catch (ClassNotFoundException e)
            {
                sResult = "Could Not Find The Database Driver";
          }
            catch (SQLException e)
            {
                sResult = "Could Not Connect To The Database";
          }
            JOptionPane.showMessageDialog(null, sResult, "Server: " + server, JOptionPane.INFORMATION_MESSAGE);
            //System.exit(0);
    }
    
}

Open in new window

0
Comment
Question by:ramanjitsingh04
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20306017
if you just want to use one single instance of a connection there is a design pattern called as singleton you can try that
http://forums.devx.com/showthread.php?t=157251

discussion on the topic related to your question

http://forum.java.sun.com/thread.jspa?threadID=5227022&messageID=9924745

or have a look at

http://www.developer.com/java/other/article.php/626291
0
 

Author Comment

by:ramanjitsingh04
ID: 20306514
Hey, Thanks for the links. But I can't figure out how to intergrate it to my code. All the examples use static final data, making the classes static. I need the data to be dynamic. As you can see the code itself gets the input from the pull down menu on the login screen and changes the server ip and server name based of it. I rather not use external property files (the ppl using this application, aren't very computer savy). That's why I need everything built into the logic. Could you point me in the direction based of the current code. If you think the current code isn't suitable to handle what I need, please if could suggest what I should do.
0
 
LVL 10

Accepted Solution

by:
adrpo earned 300 total points
ID: 20838189

Well, you could just create the connection like this:
            // String v_servername = (String) serverName.getSelectedItem();
            int v_servername = serverName.getSelectedIndex();
            Connection c = dbConnect.getFirstConnection(v_username, v_password, v_servername, false);
            // use this connection until you want another one.
            // You can just call dbConnect.getExistingConnection() anywhere you need the same connection
             
Cheers,
za-k/
/*
 * dbConnect.java
 *
 * Created on November 16, 2007, 3:33 PM
 *
 * @author cj58096
 */
 
package com.app.db;
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.swing.JOptionPane;
 
public static class dbConnect {
 
    static Connection connection = null;    
 
    /** Creates a new instance of dbConnect */    
    public static Connection getFirstConnection(String loginUsername, String loginPassword, int v_serverno) {
            
            // we want a new connection?
            if (connection != null)
            {
               connection.close();  // close the connection we have
               connection = null;
            }               
            // we need to make a connection.
            static String serverName = null;
            static String server = null;
 
            static String sResult = "Worked";            
            
            switch ( v_serverno ){
                case 0: serverName = " "; server = "P"; break;
                case 1: serverName = " "; server = "IM"; break; 
                case 2: serverName = " "; server = "OS"; break; 
                case 3: serverName = " "; server = "Q"; break; 
                case 4: serverName = " "; server = "IMQ"; break; 
                case 5: serverName = " "; server = "OSQ"; break; 
                case 6: serverName = " "; server = "T"; break; 
                case 7: serverName = " "; server = "IT"; break; 
                case 8: serverName = " "; server = "OT"; break; 
                case 9: serverName = "192.168.1.4"; server = "World"; break;
            }
    try
            {
            // Load the JDBC driver
              String driverName = "oracle.jdbc.driver.OracleDriver";
              Class.forName(driverName);
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
 
            // Create a connection to the database
              String portNumber = "1521";
              String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + server;
              connection = DriverManager.getConnection(url, loginUsername, loginPassword);
          }
            catch (ClassNotFoundException e)
            {
                sResult = "Could Not Find The Database Driver";
                connection = null;
          }
            catch (SQLException e)
            {
                sResult = "Could Not Connect To The Database";
                connection = null;
          } 
          JOptionPane.showMessageDialog(null, sResult, "Server: " + server, JOptionPane.INFORMATION_MESSAGE);
          return connection;
    }
 
    public static Connection getExistingConnection()
    {
        return connection;
    }
}

Open in new window

0
 
LVL 10

Assisted Solution

by:adrpo
adrpo earned 300 total points
ID: 20838213
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 44
String array comparison 4 55
Java syntax, or is it Selenium 6 57
wild fly 8 startup error 2 74
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question