1. 程式人生 > >JDBC用ConnectionFactory建立資料庫連線

JDBC用ConnectionFactory建立資料庫連線

package com.cjx913;

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 test {

	public static void main(String[] args) {
		List<Student> list = fecthData();

		for (Student s : list) {
			System.out.println(s);
		}
		
		
		insertData(13, "z", "6");
		

	}

	private static void insertData(int id,String name,String stu_class){
		Connection conn = null;
		PreparedStatement ps = null;
		boolean isExist = false;
		conn = ConnectionFactory.getConnection();
		try {
			ps = conn.prepareStatement("SELECT id FROM Student");
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				if(rs.getInt(1)==id){
					isExist = true;
				
				}
			}
			if(!isExist){
				ps = conn.prepareStatement("INSERT INTO Student VALUES(?,?,?)");
				ps.setInt(1, id);
				ps.setString(2, name);
				ps.setString(3, stu_class);
				ps.executeUpdate();
				System.out.println("Insert Succeed!");
			}
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private static List<Student> fecthData() {
		Student student = null;
		List<Student> list = new ArrayList<Student>();
		Connection conn = ConnectionFactory.getConnection();
		try {
			
			PreparedStatement ps = conn.prepareStatement("SELECT * FROM Student");
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				student = new Student();
				student.setId(rs.getInt(1));
				student.setName(rs.getString(2));
				student.setStu_class(rs.getString(3));
				list.add(student);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}

}