Java 如何在整个应用程序中使用一个数据库连接对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20666658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use one database connection object in whole application?
提问by Dhruv Kapatel
I have created this class which returns connection object. I have used MySQL database.
我创建了这个返回连接对象的类。我用过 MySQL 数据库。
public class Connect_db {
public Connection getConnection(String db_name,String user_name,String password)
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
Now all I want to do is instantiate this class once and get connection object. And I want to use this same object in entire application. Another solution will also be appreciated.
现在我想要做的就是实例化这个类一次并获取连接对象。我想在整个应用程序中使用这个相同的对象。另一种解决方案也将受到赞赏。
采纳答案by I?ya Bursov
I suppose you need singleton pattern, here is quick example:
我想你需要单例模式,这是一个简单的例子:
public class Connect_db {
static Connection con=null;
public static Connection getConnection()
{
if (con != null) return con;
// get db, user, pass from settings file
return getConnection(db, user, pass);
}
private static Connection getConnection(String db_name,String user_name,String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
then you will be able to use connection like this:
那么您将能够使用这样的连接:
Connect_db.getConnection().somemethods();
but, you should think - how this will work in multi-threaded environment, when several threads are trying to make requests to database.
但是,您应该考虑 - 当多个线程试图向数据库发出请求时,这将如何在多线程环境中工作。
回答by JosefN
very primitive way, you can get a Connection instance by
非常原始的方式,您可以通过以下方式获取 Connection 实例
Connect_db.getConnection(dbName,userName,passwd);
Connect_db.getConnection(dbName,userName,passwd);
in any class because it is static method.
在任何类中,因为它是静态方法。
public class Connect_db {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("MySQL db driver isnot on classpath");
}
}
public static Connection getConnection(String db_name,String user_name,String password) throws SQLException
{
return DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
}
}
}
if your applicaiton is mutlithreaded and should perfom well use a pool
如果您的应用程序是多线程的并且应该很好地使用池
回答by Dmitry Buslaev
I really liked Lashane's response, I used the code to create a DataSource
solution. I also redesigned it to only store DataSource
and not the Connection
, in case you do want to open multiple ones.
我真的很喜欢 Lashane 的回应,我使用代码创建了一个DataSource
解决方案。我还将它重新设计为仅存储DataSource
而不是Connection
,以防您确实想打开多个。
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class SignalDB {
private static MysqlDataSource ds = null;
public static MysqlDataSource getDataSource(String db_name) {
if (ds == null) {
// db variables set here
getDataSource(db_url, db_user, db_password, db_port);
}
ds.setDatabaseName(db_name);
return ds;
}
private static void getDataSource(String db_url, String db_user, String db_password, int db_port) {
try {
ds = new MysqlDataSource();
ds.setServerName(db_url);
ds.setUser(db_user);
ds.setPassword(db_password);
ds.setPort(db_port);
} catch (Exception e) {
System.out.println("MysqlDataSource err: " + e.getMessage());
e.printStackTrace();
}
}
}
Then you could create connections using:
然后您可以使用以下方法创建连接:
con = SignalDB.getDataSource("database_name").getConnection();
con = SignalDB.getDataSource("database_name").getConnection();
I added ability to connect to a different database every time, in some cases, like ours, it's what you need to do on the fly.
我增加了每次连接到不同数据库的能力,在某些情况下,就像我们的一样,这是您需要即时执行的操作。
Hope this helps.
希望这可以帮助。