Oracle数据库先创建一个表和添加一些数据,下面是连接数据库的具体实现。(导入jar包:ojdbc14.jar)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DemoOracle {
	public static Map<String,Object> query(){  
	    Connection connection = null;  
	    ResultSet rs = null;  
	    PreparedStatement stmt = null; 
            Map map = new HashMap();
	          
	    try {  
	        // 加载JDBC驱动  
	        Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();  
	        String url = "jdbc:oracle:thin:@localhost:1521:orcl";//thin:表示连接时采用thin模式(oracle中有两种模式),1521是端口号,orcl是数据库的sid
	              
	        String user = "SCOTT"; //用户名
	        String password = "mima";//密码  
	              
	        // 获取数据库连接  
	        connection = DriverManager.getConnection(url,user,password);   
	              
	        String sql = "select * from emp where empno = ? ";  
	        // 创建Statement对象(每一个Statement为一次数据库执行请求)  
	        stmt = connection.prepareStatement(sql);  
	              
	        // 设置参数  
	        stmt.setInt(1, 7499);  
	              
	        // 执行SQL语句  
	        rs = stmt.executeQuery();  
	              
	        // 处理查询结果 
	        ResultSetMetaData rsmd = rs.getMetaData();  
	        int num = rsmd.getColumnCount();  
	              
	        while(rs.next()){    
	            for(int i = 0;i < num;i++){  
	                String columnName = rsmd.getColumnName(i+1);  
	                map.put(columnName,rs.getString(columnName));  
	            }  
	        }  
	              
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    } finally {  
	        try {  
	            // 关闭结果集  
	            if (rs != null) {  
	                rs.close();  
	                rs = null;  
	            }  
	            // 关闭执行  
	            if (stmt != null) {  
	                stmt.close();  
	                stmt = null;  
	            }  
	            if (connection != null) {  
	                connection.close();  
	                connection = null;  
	            }  
	        } catch (SQLException e) {  
	            e.printStackTrace();  
	        }  
	    }        
	    return map;  
	}
	public static void main(String[] args) {
		Map<String,Object> map = query();
		System.out.println(map);
	}
}

posted on 2018-03-30 20:20  程序员大彬  阅读(131)  评论(0编辑  收藏  举报