Chinaunix
标题:
简单的JDBC助手类
[打印本页]
作者:
gongfuxuan
时间:
2004-11-22 17:21
标题:
简单的JDBC助手类
import java.sql.*;
public class Helper {
private Helper() {
}
public static Connection getConnection() {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url = "";
Connection con = DriverManager.getConnection(url, "gongfuxuan",
"password");
return con;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error while get database Connection");
}
}
public static ResultSet query(String sql) {
Connection con = getConnection();
ResultSet rs = null;
try {
Statement st = con.createStatement();
rs = st.executeQuery(sql);
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
catch (SQLException e) {
System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
e.getSQLState() + "when execute sql:" + sql);
}
return rs;
}
public static boolean execute(String sql) {
Connection con = getConnection();
boolean result = false;
try {
Statement st = con.createStatement();
result = st.execute(sql);
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
catch (SQLException e) {
System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
e.getSQLState() + "when execute sql:" + sql);
}
return result;
}
public static long Update(String sql) {
Connection con = getConnection();
long result = -1L;
try {
Statement st = con.createStatement();
result = st.executeUpdate(sql);
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
catch (SQLException e) {
System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
e.getSQLState() + "when execute sql:" + sql);
}
return result;
}
}
复制代码
作者:
逸远
时间:
2004-11-22 17:39
标题:
简单的JDBC助手类
呵呵~~,其实可以使用工厂模式,以后就什么数据库都可以通用了
作者:
elgs
时间:
2004-11-22 21:38
标题:
简单的JDBC助手类
有两个问题, 1, 不用连接池, 没什么实用价值, 2, 是又第一个问题导致的, 返回ResultSet必须保持住连接, 直到ResultSet用完才能关闭, 封装得不好。
不过这样设计的想法是很不错的。
如果把ResultSet里的数据导到一个其它的数据结构里,就像CachedRowSet一样, 如何
作者:
jhsea3do
时间:
2004-11-22 22:02
标题:
简单的JDBC助手类
我记得好像说JIVE在这方面处理得比较好!
作者:
gongfuxuan
时间:
2004-11-23 10:15
标题:
简单的JDBC助手类
谢谢elgs 指点,对,实际用是肯定要用连接池才行,把
getConnection()函数重写。你指出的第二点,让我很佩服,谢谢,我将修改一下。
作者:
moonight
时间:
2004-11-24 10:06
标题:
简单的JDBC助手类
这种写法我们原来也试过,但是在查询大结果集的时候和有事务处理的时候问题比较多。所以只能不封装了。
要是能有通用的解决方法就好了。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2