JDBC连接Oracle数据库及List 的遍历

好久没写关于数据库链接的代码了,居然都不会了,果断发帖纪录一下。

数据库相关的Object类:

package com.lliu.JDBC;

public class AAA {
	public AAA(){
		
	}
	public AAA(int ID, String name, String dept){
		this.setID(ID);
		this.setName(name);
		this.setDept(dept);
	}
	public int ID;
	public String name;
	public String dept;
	public int getID() {
		return ID;
	}
	public void setID(int iD) {
		ID = iD;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	
}


连接数据库并遍历其中Item:

package com.lliu.JDBC;


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


public class JDBCConnection {
	public static void main(String[] args){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<AAA> list =new ArrayList<AAA>();
		AAA a = new AAA();
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@127.0.0.1:1521:xe", 
					"system", 
					"12345");
			stmt = conn.prepareStatement("select ID,NAME,DEPT from AAA");
			rs = stmt.executeQuery();
			while(rs.next()){
				list.add(new AAA(rs.getInt(1),rs.getString(2),rs.getString(3)));
				System.out.println(rs.getString(2));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(stmt != null){
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		Iterator<AAA> it = list.iterator();
		while(it.hasNext()){
			System.out.println(it.next().ID);
		}
	}
}


积少成多,每天进步一点,加油~~~

猜你喜欢

转载自lliu26.iteye.com/blog/1496804