纯java通过jdbc向数据库添加/删除/更新数据的单个方法实现?
程序代码:我想将sql语句在调用时再声明,下面出现了一些错误,请求紧急救援
//这是一个添加,更新,删除三合一的方法
public void Change(String sql,Object [] obj){
try {
conn=getConn();//获取连接
PreparedStatement pst=conn.prepareStatement(sql);//准备对象
if(obj!=null){
for(int i=0;i<obj.length;i++){//通过外部数组取
pst.setObject(i+1, obj[i]);
}
}
int sum=pst.executeUpdate();
if(sum>0){
System.out.println("执行成功");
}else{
System.out.println("执行失败");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll(rs,pst,conn);
}
}
import java.lang.reflect.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
//测试类,seq_students.nextval是序列值
public class Test {
@SuppressWarnings("null")
public static void main(String[] args) throws SQLException {
JDBC_Connection jc=new JDBC_Connection();
PreparedStatement pst=null;
String sql="insert into students values(seq_student.nextval,?,?,?)";
Object obj []=new Object[]{};
obj[1]="janes";
obj[2]=223322;
obj[3]=1234;
jc.Change(sql, obj);
}
}

