封装链接数据库的工具

package com.coding.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DbUtils {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql:///mydb";
private static final String user = "root";
private static final String password = "root";

static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

}

public Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void close(ResultSet rs, PreparedStatement st, Connection conn) {
try {

if (rs != null)
rs.close();
if (st != null)
st.close();
if (conn != null)
conn.close();

} catch (Exception e) {
e.printStackTrace();
}

}

/**
* 封装增删改的方法
* @param sql sql语句
* @param obj 参数集
* @return
*/
public int excuteUpdate(String sql,Object...obj) {
int code=0;
Connection conn = getConnection();
PreparedStatement pstate=null;
try {
pstate = conn.prepareStatement(sql);
if(obj!=null) {
if(obj.length>0) {
for (int i = 0; i < obj.length; i++) {
pstate.setObject(i+1, obj[i]);
}
}
}
code=pstate.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(null, pstate, conn);
}


return code;

}

}

posted @ 2017-12-06 18:48  菜菜博客  阅读(364)  评论(0编辑  收藏  举报