Chinaunix首页 | 论坛 | 博客
  • 博客访问: 245157
  • 博文数量: 20
  • 博客积分: 1530
  • 博客等级: 上尉
  • 技术积分: 525
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-31 16:26
文章分类

全部博文(20)

文章存档

2018年(2)

2012年(1)

2011年(4)

2010年(5)

2009年(2)

2008年(6)

我的朋友

分类: Java

2010-09-13 16:45:06

package db;
import java.sql.*;
import java.io.*;
import java.util.Properties;
public class DBUtil{
 
 private static final String CONFIG_FILE = "db.properties";
 private static final String SERVER_NAME = "SqlServer.Host";
 private static final String SERVER_PORT = "SqlServer.Port";
 private static final String SERVER_INSTANCE = "SqlServer.InstanceName";
 private static final String SERVER_DBNAME = "SqlServer.DatabaseName";
 private static final String SERVER_USER = "SqlServer.UserName";
 private static final String SERVER_PWD = "SqlServer.Password";
 private static final String SERVER_DOMAIN = "SqlServer.Domain";
    
 private static Connection conn = null;
 private static String strHost = "";
 private static String strInstance = "";
 private static String strPort = "1433";
 private static String strDbName = "";
 private static String strUser = "";
 private static String strPassword = "";
 private static String strDomain = "";
 
 
 public DBUtil(){
  Properties prop = new Properties();
  try {
      prop.load(new FileInputStream(CONFIG_FILE));
      strHost = prop.getProperty(SERVER_NAME);
      strPort = prop.getProperty(SERVER_PORT);
      strInstance = prop.getProperty(SERVER_INSTANCE);
      strDbName = prop.getProperty(SERVER_DBNAME); 
      strUser = prop.getProperty(SERVER_USER);
      strPassword = prop.getProperty(SERVER_PWD);
      strDomain = prop.getProperty(SERVER_DOMAIN);
  } catch (IOException e) {
   e.printStackTrace();
  }
 
 }
 
 public void aquireConnect() throws Exception{
  try{
   Class.forName("net.sourceforge.jtds.jdbc.Driver");   
         conn = DriverManager.getConnection(getConnectionString());          
     }
     catch (Exception e)
     {
      System.out.println("Connection db faild with connection string:"
             + getConnectionString());
         e.printStackTrace();
        
         throw e;
     }
 }
 public void close() throws SQLException{
  conn.close();
  conn = null;
 }
 public String getConnectionString(){
  //jdbc:jtds:://[:][/][;=[;...]]
  String strConn = "jdbc:jtds:sqlserver://" + strHost + ":" + strPort + "/" + strDbName;
  
  if(strInstance != null && strInstance.length()> 0 )
   strConn += ";instance=" + strInstance + ";user=" + strUser + ";password=" + strPassword;
  else
   strConn += ";user=" + strUser + ";password=" + strPassword;
  
  if(strDomain != null && strDomain.length() > 0)
   strConn += ";domain=" + strDomain;
  
  return strConn;
 }
}
 
阅读(831) | 评论(0) | 转发(0) |
0

上一篇:开源库介绍

下一篇:常用内存检查工具

给主人留下些什么吧!~~