`
baobeituping
  • 浏览: 1064939 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

数据库连接类DataBase

阅读更多

/*
 *
 */

package com.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.logicalcobwebs.proxool.ProxoolFacade;


 
// import java.util.*;
// import org.logicalcobwebs.proxool.*;

/**
 * remark: 用于连接数据源,并提供基本的数据读取与操作方法
 *
 * @author: date:
 * @version: v1.0
 *
 * upd_remark: upd_user: upd_date:
 */

public class DataBase {
 
 Properties properties_Base = new Properties();
 private static String driver;
 private static String url;
 
 private static String pwd;
 String alias_Base = "";
 String driverClass_Base = "";
 String driverUrl_Base = "";
 String url_Base="";
 
 
 

 
 // 构造函数1
 public DataBase() {
  // this("boss_10", "boss_dev", "boss_dev2008");
  //this("BOSSSITE", "boss118119", "111189boss");
 }

 // 构造函数2
 public DataBase(String databaseName, String user, String password) {
  
 }

 
 // 数据库连接:用odbc直接连接或是由连接池进行管理
 public Connection connect(String database) throws SQLException {
  try {
   return connectjdbcpool(database);
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
 }
 public Connection connectodbc(String database) throws SQLException {

  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  /*
   if (database.equalsIgnoreCase("boss_229"))
    return DriverManager.getConnection("jdbc:odbc:" + database,
      "boss118119", "111189boss");
   else
  */
   return DriverManager.getConnection("jdbc:odbc:" + database,
     "boss_dev", "boss_dev2008");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
   return null;
  }  

 }
 /*public Connection connectjdbc(String database) throws Exception {

  try {
   return connectjdbcpool(database);
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }

 }*/
 public Connection connectjdbc(String driver,String url,String user,String password) throws SQLException {
  Connection con = null;
  try {
    Class.forName(driver);
                con = DriverManager.getConnection(url,user,password);
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
   return null;
  }
  return con;

 }
 
 public Connection connectjdbcpool(String database) throws Exception {

  try {
   return DriverManager.getConnection("proxool." + database);
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }

 }
 
 

 

 

 // 创建语句
 public Statement createStatement(Connection conn) {
  try {
   return conn.createStatement(
     java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
     java.sql.ResultSet.CONCUR_READ_ONLY);
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
 }

 // 取得记录集
 public ResultSet getRS(Statement stmt, String SQL) throws SQLException {
  return stmt.executeQuery(SQL);
 }

 // 执行SQL 语句
 public void execute(Statement stmt, String SQL) throws SQLException {
  stmt.execute(SQL);
 }

 // 取得记录集的行数。
 public int getRowCount(ResultSet RS) {
  int rowCount = 0;
  try {
   String rowStatus = "";
   int preRow = 0;
   if (RS.isBeforeFirst()) {
    rowStatus = "isBeforeFirst";
   } else {
    if (RS.isAfterLast()) {
     rowStatus = "isAfterLast";
    } else {
     rowStatus = "normal";
     preRow = RS.getRow();
    }
   }

   RS.last();
   rowCount = RS.getRow();
   if (rowStatus.equals("isBeforeFirst") || preRow == 0) {
    RS.beforeFirst();
   } else {
    if (rowStatus.equals("isAfterLast")) {
     RS.afterLast();
    } else {
     RS.absolute(preRow);
    }
   }
  } catch (SQLException e) {
   rowCount = 0;
  }
  return rowCount;
 }

 // 取得记录集的列数。
 public int getColCount(ResultSet RS) {
  int colCount = 0;
  try {
   ResultSetMetaData RSMD = RS.getMetaData();
   colCount = RSMD.getColumnCount();
  } catch (SQLException e) {
   colCount = -1;
  }
  return colCount;
 }

 // 分页
 public void absolutePage(ResultSet RS, int pageSize, int page) {
  try {
   RS.absolute(pageSize * (page - 1) + 1);
  } catch (Exception e) {
  }
 }

 // 从存储过程中得到返回值。
 public int getReturnCode(CallableStatement callablestatement, boolean flag) {
  int i = -1;
  ResultSet resultset = null;
  if (flag) {
   try {
    resultset = callablestatement.getResultSet();
    resultset.next();
    i = resultset.getInt(1);
   } catch (SQLException _ex) {
    i = -1;
   } finally {
    try {
     resultset.close();
    } catch (SQLException _ex) {
    }
   }
  }
  return i;
 }

 public void close(ResultSet rs, Statement stmt, Connection conn) {
  try {
   // if (!rs.isClosed())
   // {
   if (rs != null) {
    rs.close();
   }
   // }
  } catch (SQLException sqle) {
   // System.out.print(sqle.getMessage());
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  try {
   // if (!stmt.isClosed() && stmt !=null)
   if (stmt != null) {
    // System.out.println("stmt");
    //stmt = null;
    stmt.close();
    
   }
  } catch (Exception e2) {
   e2.printStackTrace();
  }
  try {
   // if (!conn.isClosed() && conn !=null)
   if (conn != null) {
    // System.out.println("conn");
    //conn = null;
    conn.close();
    
   }
  } catch (Exception e3) {
   e3.printStackTrace();
  }
 }

 public String getTableFields(String DataBase, String Table) {
  int rows = 0;
  String fields = "";
  try {

   Connection DBConn = connect(DataBase);
   Statement stmt = DBConn.createStatement();
   String SQL = "select column_name as COLUMN_NAME,data_type as TYPE_NAME,"
     + "isnull(character_maximum_length,0) as COLUMN_SIZE,"
     + "des.COLUMN_DESC "
     + "from information_schema.columns  isc "
     + "left join ( select sc.name as scname, sp.value as COLUMN_DESC "
     + "from sysproperties sp inner join syscolumns sc on sp.id = sc.id "
     + "and sp.smallid = sc.colid left join sysobjects so on so.id = sc.id "
     + "where so.name='"
     + Table
     + "' ) des on isc.column_name =des.scname "
     + "where table_name = '"
     + Table
     + "' order by ordinal_position asc ";

   ResultSet RS = stmt.executeQuery(SQL);
   while (RS.next()) {
    fields += RS.getString("COLUMN_NAME") + ",";
    // coltype+=RS.getString("TYPE_NAME")+",";
    // colnumber+=RS.getString("COLUMN_SIZE")+",";
    // clodesc+=RS.getString("COLUMN_DESC")+",";
    rows++;
   }
   close(RS, stmt, DBConn);
   // stmt.close();
   // RS.close();
   // DBConn.close();
   if (rows == 0) {
    return null;
   } else {
    return fields.substring(0, fields.length() - 1);
   }
  } catch (Exception e) {
   return e.getMessage();
   // e.printStackTrace();
  }
 }

 public String getTableFields(String DataBase, String Table,
   boolean TableFlag) {
  int rows = 0;
  String fields = "";
  try {

   Connection DBConn = connect(DataBase);
   Statement stmt = DBConn.createStatement();
   String SQL = "select column_name as COLUMN_NAME,data_type as TYPE_NAME,"
     + "isnull(character_maximum_length,0) as COLUMN_SIZE,"
     + "des.COLUMN_DESC "
     + "from information_schema.columns  isc "
     + "left join ( select sc.name as scname, sp.value as COLUMN_DESC "
     + "from sysproperties sp inner join syscolumns sc on sp.id = sc.id "
     + "and sp.smallid = sc.colid left join sysobjects so on so.id = sc.id "
     + "where so.name='"
     + Table
     + "' ) des on isc.column_name =des.scname "
     + "where table_name = '"
     + Table
     + "' order by ordinal_position asc ";

   ResultSet RS = stmt.executeQuery(SQL);
   while (RS.next()) {
    if (TableFlag)
     fields += Table + "." + RS.getString("COLUMN_NAME") + ",";
    else
     fields += RS.getString("COLUMN_NAME") + ",";
    // coltype+=RS.getString("TYPE_NAME")+",";
    // colnumber+=RS.getString("COLUMN_SIZE")+",";
    // clodesc+=RS.getString("COLUMN_DESC")+",";
    rows++;
   }
   close(RS, stmt, DBConn);
   // stmt.close();
   // RS.close();
   // DBConn.close();
   if (rows == 0) {
    return null;
   } else {
    return fields.substring(0, fields.length() - 1);
   }
  } catch (Exception e) {
   return e.getMessage();
   // e.printStackTrace();
  }
 }

 public String getTableFieldsDesc(String DataBase, String Table) {
  int rows = 0;
  String fieldsdesc = "";
  try {

   Connection DBConn = connect(DataBase);
   Statement stmt = DBConn.createStatement();
   String SQL = "select column_name as COLUMN_NAME,data_type as TYPE_NAME,"
     + "isnull(character_maximum_length,0) as COLUMN_SIZE,"
     + "des.COLUMN_DESC "
     + "from information_schema.columns  isc "
     + "left join ( select  sc.name as scname, sp.value as COLUMN_DESC "
     + "from sysproperties sp inner join syscolumns sc on sp.id = sc.id "
     + "and sp.smallid = sc.colid left join sysobjects so on so.id = sc.id "
     + "where so.name='"
     + Table
     + "'  ) des on isc.column_name =des.scname "
     + "where table_name = '"
     + Table
     + "' order by ordinal_position asc";

   ResultSet RS = stmt.executeQuery(SQL);
   while (RS.next()) {
    // fields+=RS.getString("COLUMN_NAME")+",";
    // coltype+=RS.getString("TYPE_NAME")+",";
    // colnumber+=RS.getString("COLUMN_SIZE")+",";
    fieldsdesc += RS.getString("COLUMN_DESC") + ",";
    rows++;
   }
   close(RS, stmt, DBConn);
   // stmt.close();
   // RS.close();
   // DBConn.close();
   if (rows == 0) {
    return null;
   } else {
    return fieldsdesc.substring(0, fieldsdesc.length() - 1);
   }
  } catch (Exception e) {
   return e.getMessage();
   // e.printStackTrace();
  }
 }

 public ResultSet getTableDesc(String DataBase, String Table) {

  try {

   Connection DBConn = connect(DataBase);
   Statement stmt = DBConn.createStatement();
   String SQL = "select column_name as COLUMN_NAME,data_type as TYPE_NAME,"
     + "isnull(character_maximum_length,0) as COLUMN_SIZE,"
     + "des.COLUMN_DESC "
     + "from information_schema.columns  isc "
     + "left join ( select    sc.name as scname, sp.value as COLUMN_DESC "
     + "from sysproperties sp inner join syscolumns sc on sp.id = sc.id "
     + "and sp.smallid = sc.colid left join sysobjects so on so.id = sc.id "
     + "where so.name='"
     + Table
     + "'   ) des on isc.column_name =des.scname "
     + "where table_name = '"
     + Table
     + "' order by ordinal_position asc";

   ResultSet RS = stmt.executeQuery(SQL);
   // DBConn.close();
   if (RS == null) {
    return null;
   } else {
    return RS;
   }
  } catch (Exception e) {
   return null;
  }
 }

 public static void maino(String[] args) throws SQLException {
  DataBase db = null;
  Connection conn = null;
  Statement stmt = null;
  ResultSet RS = null;
  String SQL = "select getdate() as 'name' select Id, Name, children from V_DicBase where 1=1 ";
  // db = new DataBase();
  // System.out.println(db.getTableFields("jobcn_boss_base", "DicBase"));
  // System.out.println(db.getTableFieldsDesc("jobcn_boss_base",
  // "DicBase"));
  try {
   db = new DataBase();
   // conn = db.connect("jobcn_boss_base");
   // stmt = conn.createStatement();
   // RS = stmt.executeQuery(SQL);
   // RS=db.getTableDesc("jobcn_boss_base", "Menu");
   // if(RS.next()) {
   // System.out.println(RS.getString(1));
   // }

   // System.out.println(conn);
   System.out.println(db
     .getTableFields("jobcn_boss_hr", "Person_Main"));
   db.close(RS, stmt, conn);

  } catch (Exception sqle) {
   sqle.printStackTrace();
  } finally {
   try {
    conn.close();
   } catch (Exception e) {
    // e.printStackTrace();
   }

  }
 }

 public Connection getPoolConnection(String poolName)
 {
  DataSource ds = null;
  Connection conn = null;
  try {
   if((conn=connectjdbcpool(poolName))==null){
    System.out.println("数据库:"+poolName+"连接池无法获取,将关闭连接池!");
    ProxoolFacade.removeConnectionPool(poolName);
    System.out.println("数据库:"+poolName+"连接池即将建立...");
    registerjdbcpool(poolName,"2","1");
    System.out.println("数据库:"+poolName+"连接池建立!");
    return connectregister(poolName);
   
    
   }
  } catch (Exception e) {
   conn = getConnection();
   
   
  }
  
  return conn;
    
    
 }
 public void registerjdbcpool(String database,String max,String min)  {

  try {
   Class.forName("net.sourceforge.jtds.jdbc.Driver");
   // Class.forName("com.mysql.jdbc.Driver");
   Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
   
   properties_Base.setProperty("proxool.maximum-connection-count",max);
   properties_Base.setProperty("proxool.minimum-connection-count", min);
   properties_Base.setProperty("proxool.house-keeping-test-sql","SELECT top 1 id from Kindergarden8_mp3 ");
   properties_Base.setProperty("user", "root");
   properties_Base.setProperty("password", "root");
   alias_Base = database;
   driverClass_Base = "net.sourceforge.jtds.jdbc.Driver";
   if(database.equals("mydb")){
    driverUrl_Base = "jdbc:mysql://localhost:3306/"+database+";";
   }
   url_Base = "proxool." + alias_Base + ":" + driverClass_Base+ ":" + driverUrl_Base;
   ProxoolFacade.registerConnectionPool(url_Base, properties_Base);
   
   //return DriverManager.getConnection("proxool." + database);
  } catch (Exception e) {
   e.printStackTrace();
   //return null;
  }

 }
 public static Connection getConnection()
 {
  Connection con = null;
  try {
   con = DriverManager.getConnection(Config.con_url,Config.con_user,Config.con_pwd);
  } catch (Exception e) {
   e.printStackTrace();
   //System.out.println("DataBase.getConnection:数据库连接错误!");
   return null;
  }
  return con;
 }
 public Connection connectregister(String database) throws SQLException {
  
  try {
   return connectjdbcpool(database);

  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }


}
 public static void main(String args[]){
  try{
  Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
  Connection connection=DriverManager.getConnection(
    "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=chat", "sa", "");
  
   Statement stmt =connection.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
  //ResultSet rs = stmt.executeQuery("exec T_GetUserMenuXml '', 'JCNEP0347','style'");
   ResultSet rs = stmt.executeQuery("select top 1 Name from USER_INFO;");
  rs.next();
  
  System.out.println(rs.getString("Name"));//odbc
  //System.out.println(rs.getBinaryStream(1));//odbc
  //System.out.println(rs.getCharacterStream(1));

 
  // System.out.println(RS.getCharacterStream(1));

  // InputStream is =RS.getBinaryStream(1);
  // //RS.getBinaryStream(1);//odbc
  // InputStreamReader isr = new
  // InputStreamReader(is,"UnicodeLittle");
  // while ((c = isr.read()) != -1)
  // {
  // //System.out.println((char)c);
  // sb.append((char)c);
  // }

  // sb.append(RS.getString(1));
  // temp=RS.getString(1);
  // temp=temp.getBytes("GBK");

  // System.out.println("");
  // System.out.println("");
  // sb.append(temp);
  
  

  stmt.close();

  connection.close();
  System.out.println("ok");


  }catch(Exception ex){
   ex.printStackTrace();
  }
 }

}

分享到:
评论

相关推荐

    各种数据库连接工具Database4,用起来很方便

    Database4是一款功能强大的数据库连接工具,专为用户提供方便快捷的多数据库管理体验。这款软件支持多种类型的数据库连接,包括但不限于MySQL、Oracle、SQL Server、PostgreSQL、SQLite等,让用户能够在一个统一的...

    用工厂模式开发多数据库连接类

    例如,Java中的JDBC(Java Database Connectivity)提供了一套API来创建数据库连接,执行SQL命令并处理结果集。 接下来,我们引入工厂模式。工厂模式的核心是定义一个创建对象的接口,让子类决定实例化哪一个类。...

    简单实用的php mysql数据库连接类

    // 假设这就是我们的数据库连接类 $db = new Database('localhost', 'username', 'password', 'database_name'); if (!$db->connect()) { die('连接失败: ' . $db->getError()); } // 执行查询 $result = $db->...

    数据库连接包 DataBase connector

    提供数据库的连接功能 Database connector

    常用jdbc数据库连接jar包,数据库连接池jar包

    这些接口和类定义了如何打开、关闭数据库连接,执行SQL语句,处理结果集等操作。JDBC驱动程序是实现这些接口和类的具体数据库供应商提供的实现,比如Oracle JDBC驱动、MySQL Connector/J等。这些驱动通常以jar文件的...

    比较完整SQl数据库和As数据库连接类

    SQL(Structured Query Language)和AS数据库连接类是两种不同的数据管理方式,它们各有优劣。这里我们将深入探讨SQL数据库和AS数据库连接类,以及如何进行比较。 首先,SQL数据库,全称为结构化查询语言数据库,是...

    Database4.zip

    数据库工具Database4,各种数据库连接方便; 数据库工具Database4,各种数据库连接方便; 数据库工具Database4,各种数据库连接方便; 数据库工具Database4,各种数据库连接方便; 数据库工具Database4,各种数据库连接...

    如何查看sql server数据库连接数

    查看 SQL Server 数据库连接数的多种方法 SQL Server 数据库连接数是一个重要的性能指标,它可以帮助数据库管理员了解当前数据库的工作负载和性能。查看数据库连接数有多种方法,本文将介绍四种不同的方法来查看 ...

    数据库连接池(database connection pool)是在 Java 中用于管理数据库连接的一种技术

    数据库连接池(database connection pool)是在 Java 中用于管理数据库连接的一种技术。它的主要目的是提高数据库连接的重用性和性能。在传统的数据库连接方式中,每次与数据库建立连接时都需要进行一系列的网络通信...

    JSP应用开发-web项目创建和数据库连接类的设计.pptx

    JDBC(Java DataBase Connectivity,Java 数据库连接)是一种用于执行 SQL 语句的 Java API,可以为多种关系数据库提供统一访问。JDBC 由一组用 Java 语言编写的类和接口组成。JDBC 可以完成三件事,即与数据库建立...

    数据库连接的4种方式

    本文将深入探讨四种常见的数据库连接方式,分别是:JDBC(Java Database Connectivity)、ODBC(Open Database Connectivity)、连接池以及ORM(Object-Relational Mapping)框架。 1. JDBC(Java Database ...

    C++连接数据库,连接类

    本教程将聚焦于如何在C++中实现数据库连接,主要使用面向对象的方法,即通过创建一个连接类来处理数据库交互。我们将探讨MFC(Microsoft Foundation Classes)库,这是一个为Windows应用程序开发提供支持的C++库,它...

    C#连接数据库——Database.cs(类)

    ### 一、C#中的Database类设计 `Database.cs`类被设计用于封装与数据库交互的所有功能,包括但不限于连接数据库、执行查询、执行SQL语句以及检查数据是否存在等操作。此类的实现有助于简化代码结构,提高代码复用性...

    Delphi几种数据库连接

    在IT行业中,数据库连接是应用程序开发中的重要环节,特别是在使用Delphi这种强大的Windows应用程序开发工具时。Delphi提供了多种方式来连接和操作数据库,使得开发者能够灵活地选择适合项目需求的解决方案。以下将...

    VB如何与ACCESS数据库连接(多种方法总结)

    "VB如何与ACCESS数据库连接(多种方法总结)" VB如何与ACCESS数据库连接是VB开发中非常常见的一种操作。下面我们将总结三种不同的方法来实现VB与ACCESS数据库的连接。 方法一:使用 Database 对象 在 VB 中,我们...

    连接数据库JAVA类文件

    这些类通常包含方法来建立、管理和关闭数据库连接,执行SQL查询,以及处理结果集。描述中的"一个资源文件,一个数据源连接文件和一个DBO处理文件"揭示了实现这一功能的三个关键组成部分。 1. **DBConnection.java**...

    连接derby数据库方法—附图

    Derby数据库连接方法详解 Derby数据库连接方法是Java应用程序连接Derby数据库的主要方式。 Derby数据库是一种嵌入式关系数据库管理系统,可以嵌入到Java应用程序中,提供了一个轻量级、可靠的数据库解决方案。 ...

    delphi数据库连接池

    Delphi数据库连接池是一种高效的数据库资源管理技术,它允许应用程序在多用户环境下共享数据库连接,以提高性能并减少系统资源的消耗。连接池的核心思想是重用已建立的数据库连接,而不是每次需要时都创建新的连接,...

Global site tag (gtag.js) - Google Analytics