Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static connection

 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


[ April 21, 2006: Message edited by: stu derby ]
[ April 21, 2006: Message edited by: stu derby ]
 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As simple as checking to see if the Connection was null before creating a new one... Thanks Stu

Eric
 
stu derby
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic