[英]Too Many Client Task Exception in Java JDBC
我正在通过JAVA程序创建JDBC ODBC连接。 我必须多次进行这种连接。 一段时间后,程序将引发“太多客户端任务异常”。 如何才能解决这个问题。 我正在粘贴我的要求的示例示例
class connectiondemo
{
public void connect()
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:dsn");
Statement st= con.createStatement();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
calling programs
class
{
public static void main(String args[])
{
//supose i have to call connect methods thousands of times then what is the solution
connectdemo demo= new connectdemo();
dem0.connect();
}
}
似乎您打开的数据库连接过多,没有关闭它们。 在该连接上执行jdbc语句时,需要确保在完成连接后关闭连接。 但是,如果您忘记了,Java的垃圾收集器将在清理过时的对象时关闭连接。
依靠垃圾回收,特别是在数据库编程中,是非常差劲的编程实践。 您应该养成始终使用与连接对象关联的close()方法关闭连接的习惯。
也许添加一个finally块应该对您有帮助,如下所示:
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:dsn:);
Statement st= con.createStatement();
}
catch(Exception ex)
{
ex.printStackTrace();
} finally {
try{
con.close();
} catch (Exception e) {
}
}
}
您实际上需要多少个连接? 选项包括:
我怀疑第一种选择可能是适合您的应用程序的选择。 在这种情况下,请连接一次并共享连接,否则您的DBA可能会有话要说:
public static Connection getConnection() {
if(connection == null) {
//make and store connection globally
}
return connection;
}
public static void closeConnection() {
if(connection != null) {
//close connection
}
}
public void clientMethod() {
<SomeClass>.getConnection().prepareStatement("whatever");
}
建立数据库连接是一项昂贵的工作,并且将对应用程序的性能产生显着影响,请尽可能少地执行几次。
关键是保存连接。为什么不使用静态方法来调用连接,如下所示:
public class Connector {
private static final String URL = "jdbc:mysql://localhost/";
private static final String LOGIN = "root";
private static final String PASSWORD = "azerty";
private static final String DBNAME = "videotheque";
private static Connector connector;
private static Connection connection;
private Connector() {
}
public synchronized static Connector getInstance() {
if (connector == null) {
connector = new Connector();
}
return connector;
}
public static Connection getConnection() {
if (connection == null) {
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c;
}
return connection;
}
对于连接,您可以将其用作:
Connector.getInstance().getConnection()
由于许多原因,这看起来不好看。 考虑到您的编程水平,我建议您不要尝试自己编写此代码。 更好地获取和使用其他人编写的连接池,例如Apache DBCP库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.