JDBC在程序中用到的频率很高,本着相同代码只写一次的原则,我们将JDBC的源码封装,使用起来更加方便
下面是JDBC的基类,使用的时候只需继承此类调用其中的方法进行传参
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;
public class BaseDao {
private static final String DRIVERNAME = “oracle.jdbc.driver.OracleDriver”;
private static final String UID = "";//数据库用户名
private static final String PWD = "";//数据库密码
private static final String URL = "jdbc:oracle:thin:@10.25.49.8:1521:orcl";//只需替换ip即可
static {// 在类加载时执行一次且仅一次
try {
Class.forName(DRIVERNAME);
System.out.println("加载驱动成功!");
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败");
}
}
//insert和selecet只需继承此类并调用query方法传参即可
public Result query(String sql, Object[] args) {
int i = -1;
Connection connection = null;
Result r = null;
try {
connection = DriverManager.getConnection(URL, UID, PWD);
PreparedStatement ps = connection.prepareStatement(sql);
if (args == null || args.length == 0) {
// 无占位符,则不必传值;
} else {
for (int j = 0; j < args.length; j++) {
ps.setObject(j + 1, args[j]);
}
}
System.out.println("gdl");
ResultSet rs = ps.executeQuery();
r = ResultSupport.toResult(rs);
rs.close();
ps.close();
} catch (Exception e) {
System.out.println("查询失败:" + sql + "\r\n" + e.getMessage());
} finally {
try {
connection.close();
} catch (SQLException e) {
System.out.println("执行失败:" + e.getMessage());
}
}
return r;
}
//update只需继承此类并调用update方法传参即可
public int update(String sql, Object[] args) {
int i = -1;
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, UID, PWD);
PreparedStatement ps = connection.prepareStatement(sql);
if (args == null || args.length == 0) {
// 无占位符,则不必传值;
} else {
for (int j = 0; j < args.length; j++) {
ps.setObject(j + 1, args[j]);
}
}
i = ps.executeUpdate();
System.out.println(i+"怎么回事");
ps.close();
} catch (Exception e) {
System.out.println("执行失败:" + e.getMessage());
} finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return i;
}
}