Java02:使用Jdbc连接Oracle数据库

Java02:使用Jdbc连接Oracle数据库

Java02:使用Jdbc连接Oracle数据库

一、编写代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTest02 {

    public static void main(String[] args) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            String driver = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String user = "xuanyuan";
            String password = "xuanyuan";

            Class.forName(driver);
            con = DriverManager.getConnection(url, user, password);

            st = con.createStatement();
            rs = st.executeQuery("select sysdate from dual");

            while (rs.next())
                System.out.println(rs.getString(1));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

二、编译代码

$ javac JdbcTest02.java

三、运行程序 JdbcTest02

$ java -cp /opt/javalib/orajdbc/ojdbc14.jar:. JdbcTest02
2009-10-31 14:34:50.0

说明:Oracle和MySQL的jdbc 驱动都在 /opt/javalib/目录下
轩辕高端LinuxC/C++ACEBoost高性能服务器端应用 开发技术培训

你可能感兴趣的:(Java02:使用Jdbc连接Oracle数据库)