加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

JDBC简单连接Oracle

发布时间:2020-12-15 03:16:50 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 JDBC Connect to a data source,like a database Send queries and update statements to the database。 Retrieve and process the results received

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

JDBC

  • Connect to a data source,like a database
  • Send queries and update statements to the database。
  • Retrieve and process the results received from the database in answer to your query
package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class jdbc_exp {

    public static void main(String[] args) {
        Connection con = null;// 创建一个数据库连接
        PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
        ResultSet result = null;// 创建一个结果集对象
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
            System.out.println("开始尝试连接数据库!");
            String url = "jdbc:oracle:" + "thin:@10.224.188.188:1521:tonytest";// 127.0.0.1是本机地址,XE是精简版Oracle的默认数据库名
            String user = "hr";// 用户名,系统默认的账户名
            String password = "CCM%lab123";// 你安装时选设置的密码
            con = DriverManager.getConnection(url,user,password);// 获取连接
            System.out.println("连接成功!");
            String sql = "select * from dept order by 1";// 预编译语句,“?”代表参数
            pre = con.prepareStatement(sql);// 实例化预编译语句
            result = pre.executeQuery();// 执行查询,注意括号中不需要再加参数
            while (result.next())
                // 当结果集不为空时
                System.out.println("deptno: " + result.getInt("deptno") + " dname: "
                        + result.getString("dname") + " loc: " + result.getString("loc")
                        + " create_date: " + result.getString("create_date"));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
                // 注意关闭的顺序,最后使用的最先关闭
                if (result != null)
                    result.close();
                if (pre != null)
                    pre.close();
                if (con != null)
                    con.close();
                System.out.println("数据库连接已关闭!");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }

}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读