Linux/UNIX、C++、Boost、ACE、Shell

Linux C++训练营

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高性能服务器端应用 开发技术培训

posted on 2013-09-03 15:03 athxy 阅读(380) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理