您的位置:首页 > 数据库

封装数据库的连接的方法(用Properties类获得文件里面相应的内容)

2009-08-04 19:36 489 查看
 

import java.sql.*;
import java.util.Properties;
import java.io.*;

public class ConnOracle {
 public ConnOracle() {
 }

 private String username = "";
 private String password = "";
 private String sdriver = "";
 private String surl = "";
 Properties ppt;
 FileInputStream fis;
 Connection con = null;

 public Connection conOrcl() {
  if (sdriver == "" || surl == " ") {
   ppt = new Properties();

   try {
    fis = new FileInputStream("photo//db.ini");
    ppt.load(fis);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  this.sdriver = ppt.getProperty("driver");
  this.surl = ppt.getProperty("url");
  this.username = ppt.getProperty("user");
  this.password = ppt.getProperty("password");
  try {
   Class.forName(sdriver);
   con = DriverManager.getConnection(surl, username, password);
   System.out.println("连接成功");

  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return con;
 }

 public static void main(String[] args) {
  Connection conn;
  Statement stmt;
  ResultSet rs;
  ConnOracle co = new ConnOracle();
  conn = co.conOrcl();

  try {
   stmt = conn.createStatement();
   String sql = "select empno,ename,sal from emp where sal is not null";
   rs = stmt.executeQuery(sql);
   while (rs.next()) {
    System.out.print("员工编号" + " " + rs.getInt(1));
    System.out.print("姓名" + " " + rs.getString(2));
    System.out.println("薪水" + " " + rs.getDouble(3));
    System.out.println("**********************************");

   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

文件为photo/db.ini,里面的内容为:

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=scott
password=password

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐