package com.hfuu.xl.db;
import java.*;
import org.apache.log4j.Logger;
public class Connect{
private java.sql.Connection con = null;
private final String url = "jdbc:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "master";
private final String userName = "sa";
private final String password = "123456";
private final String selectMethod = "cursor";
private static Logger logger=Logger.getLogger(JDBCTest.class);
public Connect(){}
private String getConnectionUrl(){
// String url = "jdbc:sqlserver://localhost:1433;databaseName=" + dbName;
return url+serverName+":"+portNumber+";databaseName="+databaseName;
}
private java.sql.Connection getConnection(){
logger.info("--开始连接");
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) logger.info("--加载成功");
}catch(Exception e){
logger.info("--加载异常");
e.printStackTrace();
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
logger.info("--已连接上,正在读取数据。。。");
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else {
logger.info("--获取连接失败");
} }catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
logger.info("--开始执行");
Connect myDbTest = new Connect();
myDbTest.displayDbProperties();
logger.info("--程序执行完毕");
}
}
微软官方测试jdbc,经修改
最新推荐文章于 2024-09-01 15:30:33 发布