您的位置:首页 > 其它

jdbc连接工具类

2017-04-13 18:10 274 查看
package com.crm.util.vc;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

/**

 * 数据库连接与关闭工具类。

 * @author guoqiang

 */

public class DBHelper {
private static String driver = 
"com.microsoft.sqlserver.jdbc.SQLServerDriver";// 数据库驱动字符串
//本机
private static String url = 
"jdbc:sqlserver://localhost:1433;DatabaseName=oldmanv10";// 连接URL字符串
private static String user = "sa"; // 数据库用户名
private static String password = "123"; // 用户密码

protected Connection conn;
protected PreparedStatement pstmt;
protected ResultSet rs;
/**
* 获取数据库连接对象。
*/
public Connection getConnection() {
Connection conn = null;// 数据连接对象
// 获取连接并捕获异常
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);

// Context ctx=new InitialContext();

// DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/EasyBuy");

// conn=ds.getConnection();
} catch (Exception e) {
e.printStackTrace();// 异常处理
}
return conn;// 返回连接对象
}
/**
* 关闭数据库连接。
* @param conn 数据库连接
* @param stmt Statement对象
* @param rs 结果集
*/
public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
// 若结果集对象不为空,则关闭
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 若Statement对象不为空,则关闭
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 若数据库连接对象不为空,则关闭
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 增、删、改操作
* @param sql sql语句
* @param prams 参数数组
* @return 执行结果
*/
public int exceuteUpdate(String sql,Object...prams){
int result=0;
conn=this.getConnection();
try {
pstmt=conn.prepareStatement(sql);
if(prams!=null){
for(int i=0;i<prams.length;i++){
pstmt.setObject(i+1, prams[i]);

}
}
result=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally{
closeAll(conn, pstmt, rs);
}
return result;
}
/**
* 查
*/
public ResultSet exceuteQuery(String sql,Object...prams){

conn=this.getConnection();
try {
pstmt=conn.prepareStatement(sql);
if(prams!=null){
for(int i=0;i<prams.length;i++){
pstmt.setObject(i+1, prams[i]);

}
}
rs=pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: