JDBC连接Jar包地址
http://download.csdn.net/download/qq_26981913/10229910
SQL Server数据库连接工具类
package com.xin.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据库工具类(获取连接、释放资源)
*/
public class JdbcUtils {
private static String jdbcUrl = "jdbc:sqlserver://*.*.*.*;DatabaseName=DB_Name";
private static String jdbcUser = "username";
private static String jdbcPwd = "pwd";
// 只需要执行一次
static{
try {
// System.out.println("注册数据库驱动......");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("注册数据库驱动出现异常:"+e.getMessage());
}
}
/**
* 获取一个连接对象
* @return Connection
*/
public static Connection getConn() {
try {
return DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);
} catch (SQLException ex1) {
System.err.println("获取连接异常-->"+ex1.getMessage());
throw new RuntimeException("无法获取连接,原因:"+ex1.getMessage());
}
}
/**
* 释放资源
*/
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (null != rs) {
rs.close();
System.out.println("ResultSet已关闭!");
}
} catch (SQLException e) {
throw new RuntimeException("关闭ResultSet出现异常:" + e.getMessage());
} finally {
try {
if (null != st) {
st.close();
System.out.println("Statement已关闭!");
}
} catch (SQLException e) {
throw new RuntimeException("关闭Statement出现异常:" + e.getMessage());
} finally {
if (null != conn) {
try {
conn.close();
System.out.println("Connection已关闭!");
} catch (SQLException e) {
throw new RuntimeException("关闭Connection出现异常:"
+ e.getMessage());
}
}
}
}
}
}