JDBC代码实现

数据库结构:

表:

 

 t_course:

 

 t_course_teacher:

 

 

 t_student:

 

 t_student_course:

 

 t_teacher:

代码结构:

 

 

Dao包下的代码;

package dao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.ConnectionUtil;

public class Dao<T> {
	private Class<T> clazz;

	@SuppressWarnings("unchecked")
	public Dao() {
		Type type = this.getClass().getGenericSuperclass();
		if (type instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) type;
			Type[] types = parameterizedType.getActualTypeArguments();
			if (type != null && types.length > 0) {
				if (types[0] instanceof Class) {
					clazz = (Class<T>) types[0];
				}
			}

		}
	}

	public T querOne(String sql, Object... args) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		T entity = null;
		try {
			connection = ConnectionUtil.getConnection();
			preparedStatement=connection.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				preparedStatement.setObject(i + 1, args[i]);
				
			}
			
			resultSet = preparedStatement.executeQuery();
			if (resultSet != null) {
				ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); // 获取元数据
				int colCounts = resultSetMetaData.getColumnCount();// 获取列数
				if (resultSet.next()) {
					entity = clazz.newInstance();
					for (int i = 0; i < colCounts; i++) {
						String colname = resultSetMetaData
								.getColumnLabel(i + 1);
						System.out.println(colname);
						Object colValue = resultSet.getObject(i + 1);
						Field field = clazz.getDeclaredField(colname);
						field.setAccessible(true);
						if (colValue instanceof BigDecimal) {
							double value = ((BigDecimal) colValue)
									.doubleValue();
							System.out.println(value);
							field.set(entity, value);
						} else {
							field.set(entity, colValue);
						}
						field.setAccessible(false);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ConnectionUtil
						.release(resultSet, preparedStatement, connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return entity;
	}

	
	public List<T> querMany(String sql, Object... args) {
		List<T> entitys=new ArrayList<T>();
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		T entity = null;
		try {
			connection = ConnectionUtil.getConnection();
			preparedStatement=connection.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				preparedStatement.setObject(i + 1, args[i]);
				
			}
			
			resultSet = preparedStatement.executeQuery();
			if (resultSet != null) {
				ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); //  获取结果集元数据,获取查询集中有几列,各个列的名称是什么
				int colCounts = resultSetMetaData.getColumnCount();// 获取列数
				
				while (resultSet.next()) {            //使内部游标推进到下一条记录
					entity = clazz.newInstance();
					for (int i = 0; i < colCounts; i++) {
						String colname = resultSetMetaData
								.getColumnLabel(i + 1);
						System.out.println(colname);
						Object colValue = resultSet.getObject(i + 1);
						Field field = clazz.getDeclaredField(colname);
						field.setAccessible(true);
						if (colValue instanceof BigDecimal) {
							double value = ((BigDecimal) colValue)
									.doubleValue();
							System.out.println(value);
							field.set(entity, value);
						} else {
							field.set(entity, colValue);
						}
						field.setAccessible(false);
					}
					entitys.add(entity);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ConnectionUtil
						.release(resultSet, preparedStatement, connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return entitys;
	}
	
	
	
	public static void update(String sql, Object... args) throws Exception {
		Connection conn = null;
		PreparedStatement preparedStatement = null;
		try {
			conn = ConnectionUtil.getConnection();
			preparedStatement = conn.prepareStatement(sql);

			for (int i = 0; i < args.length; i++) {
				preparedStatement.setObject(i + 1, args[i]);
			}
			preparedStatement.executeUpdate();
		} finally {
			try {
				ConnectionUtil.release(null, preparedStatement, conn);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}



package dao;

import entity.Course;

public class CourseDao extends Dao<Course>{

}




package dao;

import entity.Student;

public class StudentDao extends Dao<Student> {

}
  

entity下的代码:

package entity;

/**
 * @author mabin
 *Data 2020-9-6
 * PackageName entity
 *ProjectName JDBC00
 *FileName Course.java
 *TODO TODO
 */


public class Course {
private String c_no;
private String c_name;
private String c_type;
private double c_credit;
private int c_time;

public Course() {
	// TODO Auto-generated constructor stub
}

public Course(String c_no,String c_name,String c_type,double c_credit,int c_time) {
	this.c_no=c_no;
	this.c_name=c_name;
	this.c_type=c_type;
	this.c_credit=c_credit;
	this.c_time=c_time;

	
}
public String getC_no() {
	return c_no;
}
public void setC_no(String c_no) {
	this.c_no = c_no;
}
public String getC_name() {
	return c_name;
}
public void setC_name(String c_name) {
	this.c_name = c_name;
}
public String getC_type() {
	return c_type;
}
public void setC_type(String c_type) {
	this.c_type = c_type;
}
public double getC_credit() {
	return c_credit;
}
public void setC_credit(double c_credit) {
	this.c_credit = c_credit;
}
public int getC_time() {
	return c_time;
}
public void setC_time(int c_time) {
	this.c_time = c_time;
}
@Override
public String toString() {
	return "Course [c_no=" + c_no + ", c_name=" + c_name + ", c_type=" + c_type
			+ ", c_credit=" + c_credit + ", c_time=" + c_time + "]";
}


}




package entity;

import java.util.Date;

public class Student {
	private String s_no;
	private String s_name;
	private String s_grade;
	private Date s_birdth;
	private String s_majer;
	private String s_class;
	private String s_phone;
	private String s_addr;

	public Student(){
		
	}
	public Student(String s_no, String s_name, String s_grade, Date s_birdth,
			String majer, String s_class, String s_phone, String s_addr) {

		this.s_no = s_no;
		this.s_name = s_name;
		this.s_grade = s_grade;
		this.s_birdth = s_birdth;
		this.s_majer = majer;
		this.s_class = s_class;
		this.s_phone = s_phone;
		this.s_addr = s_addr;
	}

	public String getS_no() {
		return s_no;
	}

	public void setS_no(String s_no) {
		this.s_no = s_no;
	}

	public String getS_name() {
		return s_name;
	}

	public void setS_name(String s_name) {
		this.s_name = s_name;
	}

	public String getS_grade() {
		return s_grade;
	}

	public void setS_grade(String s_grade) {
		this.s_grade = s_grade;
	}

	public Date getS_birdth() {
		return s_birdth;
	}

	public void setS_birdth(Date s_birdth) {
		this.s_birdth = s_birdth;
	}

	public String getMajer() {
		return s_majer;
	}

	public void setMajer(String majer) {
		this.s_majer = majer;
	}

	public String getS_class() {
		return s_class;
	}

	public void setS_class(String s_class) {
		this.s_class = s_class;
	}

	public String getS_phone() {
		return s_phone;
	}

	public void setS_phone(String s_phone) {
		this.s_phone = s_phone;
	}

	public String getS_addr() {
		return s_addr;
	}

	public void setS_addr(String s_addr) {
		this.s_addr = s_addr;
	}

	@Override
	public String toString() {
		return "Student [s_no=" + s_no + ", s_name=" + s_name + ", s_grade="
				+ s_grade + ", s_birdth=" + s_birdth + ", majer=" + s_majer
				+ ", s_class=" + s_class + ", s_phone=" + s_phone + ", s_addr="
				+ s_addr + "]";
	}

}

  

util包下的代码:

package util;

import java.io.BufferedInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ConnectionUtil {
public static Connection getConnection() throws Exception{
	BufferedInputStream bis=new BufferedInputStream(ConnectionUtil.class.getClassLoader().getResourceAsStream("conn.properties"));
	Connection conn=null;
	Properties properties=new Properties();
	properties.load(bis);
	String driverClassName=properties.getProperty("driverclass");
	String url=properties.getProperty("url");
	String username=properties.getProperty("username");
	String password=properties.getProperty("password");
	Class.forName(driverClassName);
	conn=DriverManager.getConnection(url,username,password);
	System.out.println("连接成功!!");
	return conn;
	
}

public static void release(ResultSet resultSet,Statement statement,Connection conn)throws SQLException{
		if(statement!=null){statement.close();}
		if(conn!=null){conn.close();}
		if(resultSet!=null){resultSet.close();}
		
		System.out.println("连接已关闭");
	
}



}

  

test包下的代码:

package test;

import java.util.List;

import org.junit.Test;

import dao.CourseDao;
import dao.StudentDao;
import entity.Course;
import entity.Student;

public class DBTest {
public static void main(String[] args) {
	
}

@Test
public void courseTest(){
	String sql="select c_no,c_name,c_type from t_coures where c_no=?";
	CourseDao courseDao=new CourseDao();
	Course course1=courseDao.querOne(sql, "220141402");
	System.out.println(course1);
	
	
	String sql2="select c_no,c_name,c_type,c_credit,c_time from t_coures where c_no=?";
	CourseDao courseDao2=new CourseDao();
	Course course2=courseDao2.querOne(sql2, "220141402");
	System.out.println(course2);
}

@Test
public void studentTest(){
//	String sql="select s_no,s_name,s_grade, s_birdth,s_majer,s_class,s_phone,s_addr from t_student where s_no=?";
//	StudentDao studentDao=new StudentDao();
//	Student student1=studentDao.querOne(sql, "2020081208");
//	System.out.println(student1);
	
	
	String sql2="select s_no,s_name,s_grade, s_birdth,s_majer,s_class,s_phone,s_addr from t_student ";
	StudentDao studentDao2=new StudentDao();
	List<Student> student2=studentDao2.querMany(sql2);
	System.out.println(student2);
	
	
	
}
}

  

config文件夹下的文件:

 

 

 mysql驱动:

 

 

 

 

posted @ 2020-09-07 12:20  极地阳光-ing  阅读(162)  评论(0编辑  收藏  举报