我写了一个单例类来获取数据库连接。
现在我的问题是:假设有100个用户访问该应用程序。如果一个用户关闭了连接,对于其他99个用户,是否会关闭连接?
这是我的示例程序,它使用单例类来获取数据库连接:
public class GetConnection {
private GetConnection() { }
public Connection getConnection() {
Context ctx = new InitialContext();
DataSource ds = ctx.lookup("jndifordbconc");
Connection con = ds.getConnection();
return con;
}
public static GetConnection getInstancetoGetConnection () {
// which gives GetConnection class instance to call getConnection() on this .
}
}
请指导我。
答案 0 :(得分:24)
只要您未在Connection
电话上退回相同 getConnection()
实例,就无需担心。然后每个调用者都会获得自己的实例。到目前为止,您正在为每个getConnection()
调用创建一个全新的连接,因此不会返回一些静态或实例变量。所以这很安全。
然而,这种方法很笨拙。它不需要是单身人士。辅助工具/实用工具类也很好。或者,如果您想要更多抽象,则由抽象工厂返回连接管理器。我只会在类初始化期间更改它以获取数据源,而不是每次在getConnection()
中获取数据源。无论如何,它每次都是相同的实例。保持便宜。这是一个基本的启动示例:
public class Database {
private static DataSource dataSource;
static {
try {
dataSource = new InitialContext().lookup("jndifordbconc");
}
catch (NamingException e) {
throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
}
}
public static Connection getConnection() {
return dataSource.getConnection();
}
}
根据普通的JDBC习惯用法如下使用。
public List<Entity> list() throws SQLException {
List<Entity> entities = new ArrayList<Entity>();
try (
Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setFoo(resultSet.getString("foo"));
entity.setBar(resultSet.getString("bar"));
entities.add(entity);
}
}
return entities;
}
答案 1 :(得分:2)
package es.sm2.conexion;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConexionTest {
static Connection getConnection() throws Exception {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "userparatest";
String password = "userparatest";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName, userName,password);
return conn;
}
}
关闭连接
public static void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
}
}
要呼叫连接:
package conexion.uno;
import java.sql.*;
import es.sm2.conexion.ConexionTest;
public class LLamadorConexion {
public void llamada() {
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultado = null;
String query = "SELECT * FROM empleados";
try {
conn = ConexionTest.getConnection();
statement = conn.prepareStatement(query);
resultado = statement.executeQuery();
while (resultado.next()) {
System.out.println(resultado.getString(1) + "\t" + resultado.getString(2) + "\t" + resultado.getString(3) + "\t" );
}
}
catch (Exception e) {
System.err.println("El porque del cascar: " + e.getMessage());
}
finally {
ConexionTest.closeConnection(conn);
}
}
}
答案 2 :(得分:1)
下面的代码是一个经过工作和测试的Singleton Pattern for Java。
public class Database {
private static Database dbIsntance;
private static Connection con ;
private static Statement stmt;
private Database() {
// private constructor //
}
public static Database getInstance(){
if(dbIsntance==null){
dbIsntance= new Database();
}
return dbIsntance;
}
public Connection getConnection(){
if(con==null){
try {
String host = "jdbc:derby://localhost:1527/yourdatabasename";
String username = "yourusername";
String password = "yourpassword";
con = DriverManager.getConnection( host, username, password );
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
}
return con;
}
在任何类中获取Connection只需使用以下行
Connection con = Database.getInstance().getConnection();
希望它可能有所帮助:)
答案 3 :(得分:0)
import java.sql.Connection;
import java.sql.DriverManager;
public class sql11 {
static Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ics", "root", "077");
return c;
}
}
答案 4 :(得分:0)
很棒的帖子,farhangdon!但是,我发现这有点麻烦,因为一旦关闭连接,便没有其他方法可以开始新的连接了。一个小技巧可以解决它:
将if(con==null)
替换为if(con==null || con.isClosed())