aspose file tools*
The moose likes JDBC and the fly likes static connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "static connection" Watch "static connection" New topic
Author

static connection

Eric Gero
Ranch Hand

Joined: Jul 20, 2005
Posts: 73
Hi,
I am using the code below to create a jdbc connection to an MS SQL server. It works fine, but I was trying to make a static connection, so the app would only have one connection during its use. I noticed however that everytime I click on the connect button in my swing app, I get a new connection. Am I not understanding "static connection," or does my code not properly create a static connection?

Thanks,
Eric


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

public class DBLoader {
private static String driver "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static String conn_URL = "jdbc:microsoft:sqlserver://xxxxxxxxx;databaseName=xxxxxx;selectMethod=cursor";
private static String user = "xxxx";
private static String password = "xxx";
private static Connection conn;
private static Statement stmt;

/** Creates a new instance of DBLoader */
private DBLoader() {
}

private static DBLoader db = new DBLoader();

public static DBLoader makeConnection() {
return db;
}

public static Connection getConn() throws SQLException {
try {
Class.forName(driver);

conn = DriverManager.getConnection(conn_URL, user, password);
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333


[ April 21, 2006: Message edited by: stu derby ]
[ April 21, 2006: Message edited by: stu derby ]
Eric Gero
Ranch Hand

Joined: Jul 20, 2005
Posts: 73
As simple as checking to see if the Connection was null before creating a new one... Thanks Stu

Eric
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
Originally posted by Eric Gero:
As simple as checking to see if the Connection was null before creating a new one... Thanks Stu

Eric



I realized later that the "synchronized" on the method isn't needed; a) your application is single-threaded, and b) more than one thread can't use the same connection at a time anyway (bad things happen if you try).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static connection
 
Similar Threads
nullpointerexception
java.lang.NullPointerException
Cannot open connection issue
jsf and database connection problem
java.sql.SQLException: Server configuration denies access to data source