Java 如何正确地关闭JDBC连接以便重用?

Java 如何正确地关闭JDBC连接以便重用?,java,android,database,jdbc,Java,Android,Database,Jdbc,我能够在第一次建立连接时从数据库中检索信息,但每当我尝试重新连接到数据库并在不同的类中从数据库检索更多信息时,它都不起作用。我试图将从数据库中检索到的信息放入Android Studio中的文本视图中,但它们始终显示为“null”。我将向您展示我第一次连接到数据库、连接管理器类以及下次尝试连接到数据库时的代码。我认为这可能是因为连接未正确关闭,但我确保关闭resultSet、语句和连接 这是为我的高级项目,这是即将到期,所以任何帮助将不胜感激。谢谢 以下是我第一次连接到数据库时的代码: publ

我能够在第一次建立连接时从数据库中检索信息,但每当我尝试重新连接到数据库并在不同的类中从数据库检索更多信息时,它都不起作用。我试图将从数据库中检索到的信息放入Android Studio中的文本视图中,但它们始终显示为“null”。我将向您展示我第一次连接到数据库、连接管理器类以及下次尝试连接到数据库时的代码。我认为这可能是因为连接未正确关闭,但我确保关闭resultSet、语句和连接

这是为我的高级项目,这是即将到期,所以任何帮助将不胜感激。谢谢

以下是我第一次连接到数据库时的代码:

public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

    public final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            ResultSet resultSet = null;
            if (st != null)
                resultSet = st.executeQuery("SELECT * FROM userinfo WHERE email='" + mEmail + "'");
            int counter = 0;
            if (resultSet != null)
                while (resultSet.next()) {
                    counter++;
                    try {
                        if (mPassword.equals(resultSet.getString("password"))) {
                            UserLoginInfo.userEmail = mEmail;
                            UserLoginInfo.fName = resultSet.getString("firstname");
                            UserLoginInfo.lName = resultSet.getString("lastname");
                            st.close();
                            resultSet.close();
                            conn.close();
                            return (true);
                        } else
                            return (false);
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            if (counter == 0)
                return false;
            // TODO: register the new account here.
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onPostExecute ( final Boolean success){
        mAuthTask = null;
        showProgress(false);
        if (success) {
            finish();
            startActivity(new Intent("NavDrawer"));
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled () {
        mAuthTask = null;
        showProgress(false);
    }
}
package com.capstone.hammond.wallstreetfantasyleaguefinal;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class WeeklyMatchFragment extends Fragment {
    TextView user1;
    TextView user2;
    TextView bank1;
    TextView bank2;
    String oppFName;
    String oppLName;
    float oppBank;

View rootview;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fragment_weekly_match, container, false);
    return rootview;

}

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    new MatchDetails();

    user1 = (TextView) view.findViewById(R.id.user1);
    user1.setText(UserLoginInfo.fName + " " + UserLoginInfo.lName);
    bank1 = (TextView) view.findViewById(R.id.bank1);
    bank1.setText("Bank: " + UserLoginInfo.bank);
    user2 = (TextView) view.findViewById(R.id.user2);
    user2.setText(oppFName + " " + oppLName);
    bank2 = (TextView) view.findViewById(R.id.bank2);
    bank2.setText("Bank: " + oppBank);


}

public class MatchDetails extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();

            ResultSet rs = null;
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            if (st != null)
                rs = st.executeQuery("SELECT * FROM L1_Standings WHERE EMAIL = '" + UserLoginInfo.userEmail + "'");
            if (rs != null)
                while (rs.next()) {
                    try {
                        UserLoginInfo.bank = rs.getInt("BANK");
                        UserLoginInfo.currOpp = rs.getInt("CURR_OPP");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            Statement st1 = null;

            if (conn != null)
                st1 = conn.createStatement();
            ResultSet rs1 = null;
            if (st != null)
                rs1 = st1.executeQuery("SELECT * FROM USERINFO WHERE EMAIL = '" + UserLoginInfo.currOpp + "'");
            if (rs1 != null)
                while (rs1.next()) {
                    try {
                        oppFName = rs1.getString("FIRSTNAME");
                        oppLName = rs1.getString("LASTNAME");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

}
这是我第二次尝试连接到数据库:

public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

    public final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            ResultSet resultSet = null;
            if (st != null)
                resultSet = st.executeQuery("SELECT * FROM userinfo WHERE email='" + mEmail + "'");
            int counter = 0;
            if (resultSet != null)
                while (resultSet.next()) {
                    counter++;
                    try {
                        if (mPassword.equals(resultSet.getString("password"))) {
                            UserLoginInfo.userEmail = mEmail;
                            UserLoginInfo.fName = resultSet.getString("firstname");
                            UserLoginInfo.lName = resultSet.getString("lastname");
                            st.close();
                            resultSet.close();
                            conn.close();
                            return (true);
                        } else
                            return (false);
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            if (counter == 0)
                return false;
            // TODO: register the new account here.
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onPostExecute ( final Boolean success){
        mAuthTask = null;
        showProgress(false);
        if (success) {
            finish();
            startActivity(new Intent("NavDrawer"));
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled () {
        mAuthTask = null;
        showProgress(false);
    }
}
package com.capstone.hammond.wallstreetfantasyleaguefinal;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class WeeklyMatchFragment extends Fragment {
    TextView user1;
    TextView user2;
    TextView bank1;
    TextView bank2;
    String oppFName;
    String oppLName;
    float oppBank;

View rootview;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fragment_weekly_match, container, false);
    return rootview;

}

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    new MatchDetails();

    user1 = (TextView) view.findViewById(R.id.user1);
    user1.setText(UserLoginInfo.fName + " " + UserLoginInfo.lName);
    bank1 = (TextView) view.findViewById(R.id.bank1);
    bank1.setText("Bank: " + UserLoginInfo.bank);
    user2 = (TextView) view.findViewById(R.id.user2);
    user2.setText(oppFName + " " + oppLName);
    bank2 = (TextView) view.findViewById(R.id.bank2);
    bank2.setText("Bank: " + oppBank);


}

public class MatchDetails extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();

            ResultSet rs = null;
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            if (st != null)
                rs = st.executeQuery("SELECT * FROM L1_Standings WHERE EMAIL = '" + UserLoginInfo.userEmail + "'");
            if (rs != null)
                while (rs.next()) {
                    try {
                        UserLoginInfo.bank = rs.getInt("BANK");
                        UserLoginInfo.currOpp = rs.getInt("CURR_OPP");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            Statement st1 = null;

            if (conn != null)
                st1 = conn.createStatement();
            ResultSet rs1 = null;
            if (st != null)
                rs1 = st1.executeQuery("SELECT * FROM USERINFO WHERE EMAIL = '" + UserLoginInfo.currOpp + "'");
            if (rs1 != null)
                while (rs1.next()) {
                    try {
                        oppFName = rs1.getString("FIRSTNAME");
                        oppLName = rs1.getString("LASTNAME");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

}
package com.capstone.hammond.wallstreetfantasyleaguefinal;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.annotation.Nullable;
导入android.support.v4.app.Fragment;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.TextView;
导入java.sql.Connection;
导入java.sql.PreparedStatement;
导入java.sql.ResultSet;
导入java.sql.SQLException;
导入java.sql.Statement;
公共类WeeklyMatchFragment扩展了片段{
TextView用户1;
TextView用户2;
TextView银行1;
TextView银行2;
字符串oppFName;
字符串名称;
浮动银行;
视图根视图;
@可空
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
rootview=充气机。充气(R.layout.fragment\u weekly\u match,container,false);
返回rootview;
}
已创建视图上的公共void(视图,捆绑保存状态){
super.onViewCreated(视图,savedInstanceState);
新的匹配细节();
user1=(TextView)view.findViewById(R.id.user1);
user1.setText(UserLoginInfo.fName+“”+UserLoginInfo.lName);
bank1=(TextView)view.findViewById(R.id.bank1);
bank1.setText(“银行:+UserLoginInfo.Bank”);
user2=(TextView)view.findViewById(R.id.user2);
user2.setText(oppFName+“”+oppLName);
bank2=(TextView)view.findViewById(R.id.bank2);
bank2.setText(“银行:”+oppBank);
}
公共类MatchDetails扩展了AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
Connection conn=ConnectionManager.getConnection();
结果集rs=null;
语句st=null;
如果(conn!=null)
st=conn.createStatement();
如果(st!=null)
rs=st.executeQuery(“从L1_排名中选择*,其中EMAIL='”+UserLoginInfo.userEmail+'”;
如果(rs!=null)
while(rs.next()){
试一试{
UserLoginInfo.bank=rs.getInt(“银行”);
UserLoginInfo.currOpp=rs.getInt(“CURR_OPP”);
}捕获(SQLException e3){
e3.printStackTrace();
}
}
语句st1=null;
如果(conn!=null)
st1=conn.createStatement();
结果集rs1=null;
如果(st!=null)
rs1=st1.executeQuery(“从USERINFO中选择*,其中EMAIL='”+UserLoginInfo.currOpp+”);
如果(rs1!=null)
while(rs1.next()){
试一试{
oppFName=rs1.getString(“名字”);
oppLName=rs1.getString(“LASTNAME”);
}捕获(SQLException e3){
e3.printStackTrace();
}
}
}捕获(SQLE异常){
e、 printStackTrace();
}
返回null;
}
}
}

您应该在finally块中关闭JDBC连接

如果您使用的是JAVA 7,请使用try with resource语句-

关于您的问题:

  • 或者,您应该a)显式关闭连接b)在ConnectionManager中编写并调用执行该操作的close()方法

  • 跨多个任务重用同一连接是个坏主意。虽然这听起来不错,但在多线程环境中,它并不高效。直接连接必须尽快“关闭”。你要找的是一个连接池

  • 是的,您必须关闭每个数据库资源(按相反顺序):结果集、语句、连接

语句、结果集和连接是出站网络和数据库资源的对象包装器,因此它们不是无限的(在客户端和服务器端)。因此,在客户端和服务器端,让这些资源保持打开状态会有不同的方面


在客户端,您将某个(出站)资源(即连接)标记为忙碌,而该资源是空闲的(我的意思是,在一种使用和另一种使用之间)。如果您不释放在服务器端仍被标记为忙碌的资源(这里我指的是该资源的服务器端表示),并且由于服务器通常有有限数量的可用“插槽”,另一个客户端可能会看到拒绝的新连接请求,这是错误的,因为也许你没有真正使用它

我终于让它发挥了一些作用。最大的问题不是我第一次没有关闭连接,而是我没有正确地调用Asynctask。它必须是:

new MatchDetails().execute((Void) null);
现在我唯一的问题是文本视图在片段打开两次之前不会改变。我第一次打开它们时,它们看起来是空的,但当我再次打开它时,它们会变成它们应该是的样子。有人对此有什么想法吗?

只需用close()在中关闭它即可