Encapsulating query, adding, deleting, modifying and connecting database

Posted by anand on Sun, 20 Oct 2019 16:43:04 +0200

encapsulation

BaseDao

What if the parameter, quantity and type are not fixed?

public class TestMethod {
	//First, method overload
	/*public int sum(int a) {
		return a;
	}
	public int sum(int a,int b) {
		return a+b;
	}
	public int sum(int a,int b,int c) {
		return a+b+c;
	}*/
	
	//Method 2, put an array
	/*public int sum(int [] arr) {
		int s=0;
		for(int i:arr) {
			s+=i;
		}
		return s;
	}
	public static void main(String[] args) {
		int [] arr= {12,23};
		new TestMethod().sum(arr);
	}*/
	
	//Method 3, variable length parameters
	//There can only be one variable length parameter in a method
	//Variable length parameters can only be placed in the last position
	public int sum(int ...arr) {
		int s=0;
		for(int i:arr) {
			s+=i;
		}
		return s;
	}
	public static void main(String[] args) {
		new TestMethod().sum();
		new TestMethod().sum(100);
		new TestMethod().sum(100,200);
	}
}

Encapsulation of database

Database connection encapsulation

public Connection getConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url = "jdbc:oracle:thin:@//localhost:1521/ORCL";
			String user = "scott";
			String password = "123";
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException("The database driver is missing");
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("connection failed"+e.getMessage());
		}
	}

Package of addition, deletion and modification

public static void main(String[] args) throws SQLException {		
		Scanner input=new Scanner(System.in);
		System.out.println("Employee number");
		int empno=input.nextInt();
		System.out.println("wages");
		int sal=input.nextInt();
		String sql="update emp set sal=sal+? where empno=?";
		int rows=new BaseDao().executeUpdate(sql,sal,empno);
		if(rows>0) {
			System.out.println("Successful pay rise");
		}
		else {
			System.out.println("Unsuccessful");
		}
}

public int executeUpdate(String sql,Object ...args) {
		try {
			Connection conn=this.getConnection();
			PreparedStatement ps=conn.prepareStatement(sql);
			if(args!=null) {
				for(int i=0;i<args.length;i++) {
					if(args[i].getClass()==java.util.Date.class) {
						java.util.Date dt=(java.util.Date)args[i];
						ps.setTimestamp(i+1, new Timestamp(dt.getTime()));
					}
					else {
					ps.setObject(i+1, args[i]);
					}
				}
			}
			int rows=ps.executeUpdate();
			ps.close();
			conn.close();
			return rows;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

Encapsulation of queries

public ResultSet executeQuery(String sql,Object ... args) {
		try {
			Connection conn=this.getConnection();
			PreparedStatement ps=conn.prepareStatement(sql);
			if(args!=null) {
				for(int i=0;i<args.length;i++) {
					if(args[i].getClass()==java.util.Date.class) {
						java.util.Date dt=(java.util.Date)args[i];
						ps.setTimestamp(i+1, new Timestamp(dt.getTime()));
					}else {
						ps.setObject(i+1, args[i]);
					}
				}
			}
		  ResultSet rs=	ps.executeQuery();
		  CachedRowSet set= RowSetProvider.newFactory().createCachedRowSet();
		  set.populate(rs);
		  rs.close();
		  ps.close();
		  conn.close();
          return set;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

Encapsulation of objects

create table grade(gradeId number(10),gradeName varchar2(30) not null);

create table students(stuid number(10) not null,stuname varchar2(30),gender varchar2(2),gradeid number(10),phone varchar2(20),address varchar2(50));

alter table grade add constraint pk_gradeid primary key(gradeid);
alter table students add constraint fk_gradeid foreign key(gradeid) references grade(gradeId);
alter table students add constraint ck_gender check(gender='male' or gender='female');

insert into grade values(100,'Computer science and technology');
insert into students values(10001,'Li Yu','male',100,'19987260835','Xuchang City, Henan Province');

create sequence sql_students_stuid
increment by 1
start with 10000;

alter table students
add constraint uq_stuname unique(stuname);--Unique constraint

Dao data access object

Tool class BaseDao encapsulates common methods of executing sql statements

Entity class table - > class student

          Column - > Field

          Foreign key column object type

Interface encapsulation method of table operation (crud)

      StudentDao

Implementation class

          StudentDaoImpl

Package: XXX.dao

               Tool class BaseDao

               Interface studentdao gradedao

    XXX.dao.impl implementation class

    XXX.entity entity class

Topics: SQL Java Database Oracle