服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在java中连接oracle数据库(例子)


  /*
  * 创建日期 2005-9-27
  *
  * todo 要更改此生成的文件的模板,请转至
  * 窗口 - 首选项 - java - 代码样式 - 代码模板
  */
  package person.fane.test;
  
  import java.sql.*;
  /**
  * a jdbc test application for oracle
  * @author fane
  * @version 1.0.0
  * @since jdk1.4
  */
  public class oracletest {
  private final string oracledrivername = "oracle.jdbc.driver.oracledriver";
  
  //以下使用的test就是oracle里的表空间
  private final string oracleurltoconnect ="jdbc:oracle:thin:@192.168.0.36:1521:test";
  private connection myconnection = null;
  /**
  * to load the jdbc driver
  *
  */
  public oracletest()
  {
  try
  {
  class.forname(oracledrivername);
  }catch(classnotfoundexception ex)
  {
  system.out.println(geterrormessage(ex,"the driver loaded error,please contact to your software designer!").tostring());
  }
  }
  
  public stringbuffer geterrormessage(exception ex,string alarmmessage)
  {
  stringbuffer errorstringbuffer = new stringbuffer();
  errorstringbuffer.append(alarmmessage);
  errorstringbuffer.append(ex.getmessage());
  return errorstringbuffer;
  }
  
  /**
  * getconnection method
  * @return connection
  */
  public connection getconnection()
  {
  try
  {
  this.myconnection = drivermanager.getconnection(oracleurltoconnect,"fane","201");
  
  }catch(exception ex)
  {
  system.out.println(geterrormessage(ex,"can not get connection,please contact to your software designer!").tostring());
  }
  
  return this.myconnection;
  
  }
  
  /**
  * @param args
  */
  public static void main(string[] args) {
  oracletest myoracletest = new oracletest();
  try
  {
  connection myconnection = myoracletest.getconnection();
  
  system.out.println("now begin to excute.............");
  
  preparedstatement mypreparedstatement = myconnection.preparestatement("select area_id, area_name,ip_address,tel,area_type,pc_id from c_area_info");
  //mypreparedstatement.setint(1,2);
  resultset myresultset = mypreparedstatement.executequery();
  stringbuffer mystringbuffer = new stringbuffer();
  
  while(myresultset.next())
  {
  
  mystringbuffer.append(myresultset.getint("area_id")+" ");
  mystringbuffer.append(myresultset.getstring("area_name")+" ");
  mystringbuffer.append(myresultset.getstring("ip_address")+" ");
  mystringbuffer.append(myresultset.getstring("tel")+" ");
  mystringbuffer.append(myresultset.getint("area_type")+" ");
  mystringbuffer.append(myresultset.getint("pc_id")+"/n");
  }
  system.out.println(mystringbuffer.tostring());
  //system.out.println(new string(mystringbuffer.tostring().getbytes("iso-8859-1"),"gbk"));
  }catch(exception ex)
  {
  system.out.println(myoracletest.geterrormessage(ex,"application error,please contact to your software designer!").tostring());
  }
  
  }
  
  }

扫描关注微信公众号