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: <server_type >:// <server> [: <port>] [/<database>] [; <property >=< value> [;...]
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;
}
}