@小小工具类 (更新表)

/**
*
* 不能被继承,,工具类,不需继承...
* 代码重用,...
*
*/
public final class SQLHelper {

//细心观察,只要加载一次驱动,创建无数组..
//
//静态初始化块,只执行一次,,

static{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

}
private SQLHelper(){}

//创建连接
//静态方法,方便调用,,
public static Connection getConnection(){
String url = "jdbc:oracle:thin:@192.168.6.108:1521:orcl";
String dbname = "scott";
String dbpwd = "tiger";
try {
return DriverManager.getConnection(url, dbname, dbpwd);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}

public static boolean update(String sql,Object[] param){
Connection conn = null;
PreparedStatement stmt = null;
int rs = 0;
try {
conn = getConnection();
stmt = conn.prepareStatement(sql);
if(param != null){
//i=0  4:: 0 1 2 3
//info.getName()  java.lang.String
//java.lang.String
for(int i = 0 ; i < param.length;i++){
    if(param[i].getClass() == java.lang.Integer.class){
    stmt.setInt(i+1, (Integer)param[i]);
    }else if(param[i].getClass() == java.lang.String.class){
    stmt.setString(i+1, (String)param[i]);
    }else if(param[i].getClass() == java.util.Date.class){
    //2000-10-10 11:11:11
    //2000-10-10
    //数据库Date不认识
    //一定保存2000-10-10 11:11:11
    //timestamp 时间戳...
    stmt.setTimestamp(i+1, conDD((java.util.Date)param[i]));
    }

}
}
rs = stmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}finally{
close(null,stmt,conn);
}

return rs != 0;

}

private static java.sql.Timestamp conDD(java.util.Date d){
return new java.sql.Timestamp(d.getTime());
}
//关闭连接
public static void close(ResultSet rs ,Statement stmt,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args){
String sql = "insert into emp(empno,ename,hiredate,sal) values(?,?,?,?)";
update(sql,new Object[]{9999,"tomtom",new Date(),9999});
}

}

你可能感兴趣的:(java,oracle,sql,jdbc)