码迷,mamicode.com
首页 > 数据库 > 详细

JDBC:以面向对象的思想编写JDBC程序

时间:2015-02-11 01:49:32      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:

题目简述:

数据表中添加学生信息,并且可以通过身份证号准考证来查询学生信息。
Name        Type         Nullable Default Comments 
----------- ------------ -------- ------- -------- 
IDCARD      NUMBER(10)   Y                         
EXAMCARD    NUMBER(10)   Y                         
STUDENTNAME VARCHAR2(20) Y                         
LACATION    VARCHAR2(20) Y                         
GRADE       NUMBER(3)    Y       

测试类
package xuezaipiao3;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import xuezaipiao1.JDBC_Tools;

/**
 * 思考:
 * 向数据表中添加一条学生信息记录,那么学生信息就可以创建一个学生类来储存信息
 * 步骤:
 * 	1) Student成员变量 对应studnt数据表 
 * 	2) 创建一个方法addStudent(Student student)
 *  3) 方法中执行相应的 SQL 操作
 * @author Kevy
 *	
 */
public class thinkInJDBC {

	public static void main(String[] args) {
		Student s = getStudentFromConsole();
		addStudent(s);
		QueryStudent();
	}
	public static void QueryStudent(){
		
		int searchType = getSearchTypeFromConsole();
		Student student = searchStudent(searchType);
		printStudent(student);
	}
	
	/**
	 * 打印学生信息
	 * @param student
	 */
	private static void printStudent(Student student) {
		if(student!=null){
			System.out.println(student);
		}else{
			System.out.println("查无此人!");
		}
	}
	/**
	 * 
	 * @param searchType 1 And 2
	 * @return
	 */
	private static Student searchStudent(int searchType) {
		
		String sql = "SELECT * FROM student "
				+ "where ";
		Scanner scanner = new Scanner(System.in);
		if(searchType==1){
			System.out.print("请输入身份证:");
			int id = scanner.nextInt();
			sql = sql + "IDCARD = " +id;
		}else{
			System.out.print("请输入准考证:");
			int id = scanner.nextInt();
			sql = sql + "EXAMCARD = " +id;
		}
		
		Student student = getStudent(sql);
		scanner.close();
		return student;
	}
	
	/**
	 * 根据传入的sql返回Student对象
	 * @param sql
	 * @return
	 */
	private static Student getStudent(String sql) {
		
		Connection connection = null;
		Statement statement = null;
		ResultSet rs = null;
		Student stu = null;
		try {
			connection = JDBC_Tools.getConnection();
			statement = connection.createStatement();
			rs = statement.executeQuery(sql);
			if(rs.next()){
				stu = new Student(rs.getInt("IDCARD"),
						rs.getInt("EXAMCARD"),rs.getString("STUDENTNAME"),
						rs.getString("LACATION"),rs.getInt("GRADE"));
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			JDBC_Tools.relaseSource(rs, connection, statement);
		}
		
		
		return stu;
	}
	/**
	 * 
	 * @return 1 用身份证查询 , 2 用准考证号查询  其他无效
	 */
	@SuppressWarnings("resource")
	private static int getSearchTypeFromConsole() {
		
		System.out.println("请输入查询类型:1.身份证查询   2.准考证查询");
		System.out.print("你的选择:");
		Scanner scanner = new Scanner(System.in);
		
		int type = scanner.nextInt();
		
		if(type!=1 && type!=2){
			System.out.println("输入有误,请重新输入");
			throw new RuntimeException();
		}
		scanner.close();
		return 0;
	}
	
	/**
	 * 从控制台获取信息 并创建学生对象
	 * @return
	 */
	private static Student getStudentFromConsole() {
		
		Scanner scanner = new Scanner(System.in);
		Student student = new Student();
		
		System.out.print("IDCard:");
		student.setIDCard(scanner.nextInt());
		
		System.out.print("ExamID:");
		student.setExamID(scanner.nextInt());
		
		System.out.print("StudentName:");
		student.setStudentName(scanner.next());
		
		System.out.print("Llocation:");
		student.setLacation(scanner.next());
		
		System.out.print("Grade:");
		student.setGrade(scanner.nextInt());
		scanner.close();
		return student;
		
	}
	
	/**
	 * 添加学生信息
	 * @param student
	 */
	public static void addStudent(Student student){
		String sql = "INSERT INTO STUDENT "
				+ "VALUES("+student.getIDCard()
				+","+student.getExamID()
				+",'"+student.getStudentName()
				+"','"+student.getLacation()
				+"',"+student.getGrade()
				+")"; 
		JDBC_Tools.update(sql);
	}
}
Student类
public class Student {
	private int IDCard;
	private int ExamID;
	private String StudentName;
	private String Lacation;
	private int Grade;
	
	public Student(int iDCard, int examID, String studentName, String lacation,
			int grade) {
		super();
		IDCard = iDCard;
		ExamID = examID;
		StudentName = studentName;
		Lacation = lacation;
		Grade = grade;
	}
	
	@Override
	public String toString() {
		return "Student [IDCard=" + IDCard + ", ExamID=" + ExamID
				+ ", StudentName=" + StudentName + ", Lacation=" + Lacation
				+ ", Grade=" + Grade + "]";
	}

	public Student() {
		super();
	}
	
	public int getIDCard() {
		return IDCard;
	}
	public void setIDCard(int iDCard) {
		IDCard = iDCard;
	}
	public int getExamID() {
		return ExamID;
	}
	public void setExamID(int examID) {
		ExamID = examID;
	}
	public String getStudentName() {
		return StudentName;
	}
	public void setStudentName(String studentName) {
		StudentName = studentName;
	}
	public String getLacation() {
		return Lacation;
	}
	public void setLacation(String lacation) {
		Lacation = lacation;
	}
	public double getGrade() {
		return Grade;
	}
	public void setGrade(int grade) {
		Grade = grade;
	}
	
}

JDBC工具类
package xuezaipiao1;
/**
 * JDBC工具类
 * 封装一些简单的JDBC操作方法
 * version 1
 */
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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 JDBC_Tools {
	/**
	 * 用来执行 SQL 的方法,包括INSRT , UPDATE , DELETE,不包含SELECT
	 * 参数 String SQL语句
	 * @return int 执行了几条记录
	 */
	public static int update(String sql){
			Connection conn = null;
			Statement statement = null;
			int num = 0;
			try {
				try {
					conn = JDBC_Tools.getConnection();
				} catch (Exception e) {	
					e.printStackTrace();
				}
				statement = conn.createStatement();
				
				num = statement.executeUpdate(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				JDBC_Tools.relaseSource(conn, statement);
			}
		return num;
	}
	
	/**
	 * 用来执行 SQL 的SELECT 方法
	 */
	public static void query(String sql){
		Connection conn = null;
		Statement statement = null;
		ResultSet rs = null;
		try {
			conn = JDBC_Tools.getConnection();
			statement = conn.createStatement();
			rs = statement.executeQuery(sql);
			while(rs.next()){
				System.out.println(rs.getInt("id"));
				System.out.println(rs.getString(2));
				System.out.println(rs.getString("email"));
			}
		} catch (Exception e) {
		
			e.printStackTrace();
		}finally{
			JDBC_Tools.relaseSource(rs, conn, statement);
		}
	}
	
	/**
	 * 用来释放资源,参数是 Connection 、 Statement
	 * @param conn
	 * @param statement
	 */
	public static void relaseSource(ResultSet rs,Connection conn ,Statement statement){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JDBC_Tools.relaseSource(conn, statement);
	}
	public static void relaseSource(Connection conn ,Statement statement){
		if(statement!=null){
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		//使用两个 if ,这样即使中间出现异常,程序还是继续执行下去
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception {
		Properties properties = new Properties();
		try {
//			InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
//			properties.load(in);
			properties.load(new FileInputStream(
					"D://LearnJava//learnJDBC//Lesson2_UseStatementAndResultSet//src//jdbc.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String jdbcUrl = properties.getProperty("jdbcUrl");
		String dirverName = properties.getProperty("driver");
		try {
			Class.forName(dirverName);
		} catch (ClassNotFoundException e1) {

			e1.printStackTrace();
		}
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(jdbcUrl, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
}




JDBC:以面向对象的思想编写JDBC程序

标签:

原文地址:http://blog.csdn.net/wjw0130/article/details/43722339

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!