您的位置:首页 > 数据库

jdbc连接数据库代码

2008-02-20 09:21 357 查看
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
/**
 *
 * @author bubei
 *
 */
public class DBConn {
 String username = "sundun";

 String password = "sundun";

 String url = "jdbc:oracle:thin:@192.168.1.4:1521:sundun";

 String drivername = "oracle.jdbc.driver.OracleDriver";

 Connection conn = null;

 Statement sta = null;

 /**
  *
  * 构造函数 jdbc数据库连接
  */
 public DbConn() {

 }

 public Connection getconn() {
  try {
   try {
    Class.forName(drivername).newInstance();
   } catch (InstantiationException e) {
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    e.printStackTrace();
   }
   conn = DriverManager.getConnection(url, username, password);

  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return conn;
 }

 /**
  * 执行update,insert,delete语句 参数:sql语句
  */
 public int update(String sql) {
  int flag = 0;
  try {
   getconn();
   sta = conn.createStatement();
   flag = sta.executeUpdate(sql);
   System.out.println("执行成功 : 有" + flag + "个记录被操作");
  } catch (SQLException e) {
   e.printStackTrace();
   System.out.println("发生sql异常后状态 ! ");
  }
  return flag;

 }

 /**
  * 执行select语句 参数:sql语句
  */
 public ResultSet query(String sql) {
  ResultSet rs = null;
  try {
   getconn();
   sta = conn.createStatement();
   rs = sta.executeQuery(sql);
  } catch (SQLException e) {
   e.printStackTrace();
   System.out.println("发生sql异常后状态 ! ");
  }
  return rs;

 }

 /**
  * 关闭连接
  *
  */
 public void closeConn() {
  try {

   sta.close();
   conn.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息