gpt4 book ai didi

java - 将 SQL 连接传递给对象

转载 作者:行者123 更新时间:2023-11-29 05:40:06 25 4
gpt4 key购买 nike

注意:不是java EE问题

在 java 中,我需要将 SQL 连接作为参数从一个类传递到另一个类。但是好像接收类拿到了Connection对象但是是null,没有连接。

我读到 Java EE 使用池。但是我的项目很小,使用 JDBC 的驱动程序管理器与本地主机连接。我还读到 java 没有通过引用传递。

有什么方法可以将实时连接从一个类(class)传递到另一个类(class)?

编辑:类连接

try
{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection(
"jdbc:mysql://localhost/MYDATABASE?user="+username+"&password="+password);
return connect;
}catch(Exception e){
return null;

在我的主课中

connect c = new connect(user,pass);

最佳答案

public class Connect
{
private static Connection sharedConnection;
public static Connection createOrAccessConnection(String user,String pass, boolean forceNew){
Connection connect = sharedConnection;
try
{

Class.forName("com.mysql.jdbc.Driver");
if(forceNew || connect == null)
{
connect = DriverManager.getConnection(
"jdbc:mysql://localhost/MYDATABASE?user="+username+"&password="+password);
if(sharedConnection == null )
{
sharedConnection = connect;
}
}
return connect;
}catch(Exception e){
return null;
}
}



class Main
{
public void transactionMethod()
{
//Some code here.
//This is what you need to add.
Connection con = Connect.createConnection(user,pass,false);
Sysout(con);
AnotherClass ac = new AnotherClass();
ac.operation1(con, false);
ac.operation1(null,true);
}



class AnotherClass
{
public void operation1(Connection con, boolean createNew)
{
if(createNew || con==null)
{
con = Connect.createConnection(user,pass,false);
}
//Some code here
if(createNew)
{
//Close connection here.
}
}
}

}

关于java - 将 SQL 连接传递给对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17923399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com