大家帮我看看这个DBConnection怎么样

tangwq121 2007-12-10 10:58:06
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection {
static Connection conn=null;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/manage?" +
"user=root&password=root");

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
public static Statement getStatement(){
Statement stmt=null;
try {
stmt = getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public static PreparedStatement getPreparedStatement(String str){
PreparedStatement pstmt=null;
try {
pstmt = getConnection().prepareStatement(str);
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}

}
...全文
132 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Zero2One 2007-12-12
  • 打赏
  • 举报
回复
这个貌似不怎么样吧?每次调用这个,都要打开一个连接,而不管连接是否存在?
SINCE1978 2007-12-12
  • 打赏
  • 举报
回复
j2ee应用当然是多用户的,其实用数据库链接池的话很方便,连接数量不必太多,因为运行合理sql的连接的数据库操作都非常快,不会占用一个链接多长时间,我感觉数千的用户连接池缓存15个链接足够了,最少维持5个链接、每次5个的增长、基本上用不到这么多。当然写程序的用完链接要及时释放。
yang24201 2007-12-12
  • 打赏
  • 举报
回复
如果你要想多个用户连接数据库的话,最好是写一个数据库连接池
hanjh9527 2007-12-12
  • 打赏
  • 举报
回复
能不能给一个例子看看呢?
SINCE1978 2007-12-11
  • 打赏
  • 举报
回复
static Connection conn
链接为静态的,这样不妥吧,成了单例了,多用户共用一个链接会混乱的。
一个用户设置:conn.setAutoCommit(false);也会影响其他用户。
而且用户关闭result或statement可能会致使链接关闭。
一个用户一个db链接这应该是起码的标准。
tangwq121 2007-12-11
  • 打赏
  • 举报
回复
红杉树 :
谢谢了.我以为只用一个连接可以减少连接数呢.不知道用户之间会影响的.

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧