Home  >  Article  >  Java  >  Specific code sharing for java connection to database

Specific code sharing for java connection to database

黄舟
黄舟Original
2017-03-25 10:44:061915browse

This article mainly introduces the implementation method code of javaconnecting to the database. Has very good reference value. Let’s take a look with the editor below

Without further ado, please look at the code:

package com.shsxt.jdbcs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * jdbc步骤: java连接数据库
 *  // 导入 jar包
 *   1、加载驱动  数据库厂商提供的实现类
 *   2、获取连接  提供 url 用户名 密码
 *   3、创建处理块  可以发送SQL语句到服务器(数据库) 准备一条 SQL语句
 *   4、结果集
 *   5、分析结果集
 *   6、释放资源  先开的后放, 后打开的先放
 */
public class Demo002JDBCConnect {
  public static void main(String[] args) throws ClassNotFoundException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    String user=  "scott";
    String pwd=  "tiger";
    Connection conn = null;
    Statement s = null;
    ResultSet rs = null;
    try {
      conn = DriverManager.getConnection(url, user, pwd);
      s = conn.createStatement();
      String sql = "select deptno, dname, loc from dept";
      rs = s.executeQuery(sql);
      while(rs.next()){
        int deptno = rs.getInt(1); // 根据列号来获取值
        String dname = rs.getString("dname"); // 根据列名来获取值
        String loc = rs.getString(3);
        System.out.println(deptno + "\t" + dname + "\t" + loc);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }finally{
      if(rs!=null){
        try {
          rs.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if(s!=null){
        try {
          s.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if(conn!=null){
        try {
          conn.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

The above is the detailed content of Specific code sharing for java connection to database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn