Java/MySQL-如何从另一个类访问连接? [英] Java / MySQL - How to access connection from another class?

查看:99
本文介绍了Java/MySQL-如何从另一个类访问连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想了解Java(关于OOP),我唯一熟悉的就是MySQL.我需要在应用程序和服务器套接字的整个过程中保持数据库连接的打开状态.

I'm just getting my head around java (and OOP for that matter), the only thing I am familiar with is MySQL. I need to keep the DB connection open throughout the duration of the application, as well as a server socket.

我什至不确定他们是否都需要单独的类,但这是我到目前为止的内容:

I'm not even sure if they both need separate classes, but here's what I have so far:

http://pastebin.com/qzMFFTrY (不是全部都放在代码标签中)

http://pastebin.com/qzMFFTrY (it wouldn't all go in a code tag)

我需要的变量是第86行的 con .

The variable I need is con for line 86.

推荐答案

为什么不使用您之前建立的连接实例化DoComms?

Why not instantiate DoComms with the connection you've got earlier ?

例如第44行将是:

DoComms conn_c = new DoComms(server, con);

DoComms将保留对该连接的引用,然后在第86行使用它.

and DoComms would hold a reference to that connection and then use it at line 86.

请注意,您已获得连接,然后在实例化DoComms对象(第28行)之前,在finally 中将其关闭.因此,在完成所有处理后,您应该关闭连接.简要地:

Note that you get the connection, and then close it in the finally block before you instantiate your DoComms objects (line 28). So you should close your connection once you've finished processing everything. Briefly:

try {
  // get connection

  // do stuff in threads
}
catch {
  // handle
}
finally {
  con.close();
}

如果您的应用程序寿命长,那么我将使用连接池(例如C3P0或Apache DBCP)并根据需要打开/关闭连接.但是,您的方法可能很适合您的要求,并且我暂时不会为此担心.

If your application is long-lived, then I would use connection-pooling (e.g. C3P0 or Apache DBCP) and open/close connections as required. However your approach may well be suitable for your requirements, and I wouldn't worry about that for the moment.

这篇关于Java/MySQL-如何从另一个类访问连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆