您的位置:首页 > 编程语言

JDBC 链接案例—— 纯代码,无连接池

2015-03-08 21:09 253 查看
public class BaseDao {
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/mydb";
private String user = "";
private String password = "";
Connection conn = null;

/**
* 获取数据库链接对象
*/
public Connection getConnection(){
if(conn == null){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}

/**
* 增、删、改操作
*/
public int executeUpdate(String sql, Object[] params){
PreparedStatement pstmt = null;
int num = 0;
conn = getConnection();

try {
pstmt = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
}
num = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally{
closeAll(conn,pstmt, null);
}

}

/**
* 关闭数据库链接
*/
public void closeAll(Connection conn, Statement stmt, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}

if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}

if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: