利用JDBC访问dept表

public class Jdbc {

	public static void main(String[] args) {
		
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
			stmt=conn.createStatement();
			rs=stmt.executeQuery("select * from dept");
			
			ResultSetMetaData rsmd=rs.getMetaData();//结果集的元数据
			int count=rsmd.getColumnCount();
			for(int i=1;i<=count;i++){
				System.out.print(rsmd.getColumnName(i)+"\t");
			}
			System.out.println();
			while(rs.next()){
				for(int i=1;i<=count;i++){
					System.out.print(rs.getString(rsmd.getColumnName(i))+"\t");
				}
				System.out.println();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
运行程序,控制台输出:



你可能感兴趣的:(jdbc)