手记

一分钟教你学会用java连接Oracle数据库

package java_jdbc;
//java连接Oracle数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdbcOracleTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
   //1.加载驱动
    Connection conn=null;  //连接对象
    Statement stmt=null;  //语句对象
    ResultSet rs=null;   //数据集对象
    String url="jdbc:oracle:thin:@localhost:1521:orcl";
    String username="scott";   //Oracle数据库用户名
    String password="tiger";   //Oracle数据库密码
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        //2.获得数据库连接
        conn=DriverManager.getConnection(url,username,password);
        /*
        //判断数据库连接是否成功
        if(conn!=null)
        {
            System.out.println("Oracle数据库间接成功");
        }else{
            System.out.println("Oracle数据库连接失败");
        }
         */
        //3.创建语句对象
        stmt=conn.createStatement();
        String sql="select * from students";//students是Oracle数据库中的表名
        rs=stmt.executeQuery(sql);
        //遍历输出数据库students表中的数据
        while(rs.next())
        {
            System.out.println(rs.getInt("sid")+","+
               rs.getString("sname")+","+rs.getString("gender")+","+
               rs.getString("birthday")+","+rs.getString("marjor")+","+
               rs.getString("address"));
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

}
2.Oracle的配置:
Oracle的用户名为:scott
Oracle的密码为:tiger
数据库为:oral11g
创建的数据表为:students

20人推荐
随时随地看视频
慕课网APP