JAVA JDBC 增删改父类封装

package My;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.mysql.cj.x.protobuf.MysqlxSession.Reset;

public class selet {
	public boolean insertData(String sql,Object...objects) {//增
		Connection conn =null;
		PreparedStatement pStat=null;
		try {
		
			conn=Main.getConnection();
			//获取Prapared对象
			pStat = conn.prepareStatement(sql);
			//将?用预处理的方式替换成你要的数据 1表示第一个占位符
			if(objects!=null) {
				for(int i=0;i<objects.length;i++) {
					pStat.setObject(i+1, objects[i]);
				}
			}
			return pStat.executeUpdate()>0?true:false;
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally{
			Main.close(null, pStat, conn);
		}
		return false;
	}
}

直接继承引用

package My;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class indes extends selet {
	public boolean insertData(EMP emp) {//增
		String sql ="insert into text values(?,?)";
		return insertData(sql, emp.getQQ(),emp.getPwd());
	}
	
	public boolean delet(int Id) {//删
	
		
		String sql="delete from text where id = ?";
		return insertData(sql, Id);
	
	}
	public List<EMP> query(String s1){//查
		ArrayList<EMP> emplist=new ArrayList<EMP>();
		Connection conn = Main.getConnection();
		String sql = "select * from text where QQ=?";
		PreparedStatement pStat = null;
		ResultSet rst = null;
		try {
			//获取对象
			pStat = conn.prepareStatement(sql);
			//处理问好
			pStat.setString(1, s1);
			rst = pStat.executeQuery();
			while(rst.next()) {
				int id = rst.getInt("id");
				String QQ =rst.getString("QQ");
				String pwd =rst.getString("pwd");
				//创建实体对象数据
				EMP emp = new EMP();
				emp.setQQ(QQ);
				emp.setPwd(pwd);
				emplist.add(emp);
				return emplist;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			Main.close(rst, pStat, conn);
		}
		return null;
	}
	//改
	public boolean update (EMP emp) {
		
			String sql = "update text set pwd=?";
			return insertData(sql, emp.getPwd());
		
	}
}

你可能感兴趣的:(JDBC,Java,sql,jdbc,封装)