java使用jdbc连接数据库的几种方式
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
编程技术
package db.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import mons.logging.Log;
import mons.logging.LogFactory;
public class DbUtil {
public static final String _DefaultJNDI = "java:/comp/env/jdbc/shcnc"; private static Log log = LogFactory.getLog(DbUtil.class);
/**
*
* Utility function to clean up db usage.
*
*
* @param pResultSet
* @param pStmt
* @param pConn
*
* @exception java.sql.SQLException
*/
public static void cleanup(ResultSet pResultSet, Statement pStmt,
Connection pConn) throws SQLException {
try {
if (pResultSet != null) {
pResultSet.close();
pResultSet = null;
}
// ("Finished cleaning up connection.");
} catch (SQLException e) {
throw e;
} finally {
try {
if (pStmt != null) {
pStmt.close();
pStmt = null;
}
} catch (SQLException e) {
throw e;
} finally {
try {
if (pConn != null && !pConn.isClosed()) {
pConn.close();
pConn = null;
}
} catch (SQLException e) {
throw e;
}
}
}
}
/**
* ����Ĭ����ݿ�
*
* @param sql
* String
* @return String
*/
public static String Update(String sql) {
return Update(sql, _DefaultJNDI);
}
/**
*
* Utility function to Execute SQL Language.
*
*
* @param sql
* String
* @return String
*/
public static String Update(String strSql, String _JNDI) { Connection conn = null;
Statement stmt = null;
String strRtn = "";
try {
conn = ConnectionPool.getInstance().getConnection(_JNDI);
stmt = conn.createStatement();
stmt.executeUpdate(strSql);
strRtn = "success";
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR_SQL: " + strSql);
strRtn = e.getMessage();
} finally {
try {
DbUtil.cleanup(null, stmt, conn);
} catch (Exception e) {
}
}
return strRtn;
}
/**
*
* ݿ��ǰMAX ID,��1,��Ϊ�µ�ID
*
*
* @param fieldname
* ID�ֶ���
* @param tablename
* ����
* @return Integer �µ�ID
*/
public static long getId(String fieldname, String tablename) {
return getId(fieldname, tablename, _DefaultJNDI);
}
public static long getId(String fieldname, String tablename, String _JNDI) { Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "";
long id = 0;
sql = "select max(" + fieldname + ") from " + tablename;