直接上代码web
public class SqlUtils {
private static final String DRIVERCLASS;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
static {
DRIVERCLASS = ResourceBundle.getBundle("SqlServerJdbc").getString("driverClass");
URL = ResourceBundle.getBundle("SqlServerJdbc").getString("url");
USERNAME = ResourceBundle.getBundle("SqlServerJdbc").getString("username");
PASSWORD = ResourceBundle.getBundle("SqlServerJdbc").getString("password");
}
static {
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
// 2.获取链接
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
// Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return con;
}
// 关闭操做
public static void closeConnection(Connection con) throws SQLException {
if (con != null) {
con.close();
}
}
public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}
}
注意此工具内配合配置文件使用(SqlServerJdbc.properties),配置文件内容以下:sql
driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://IP;databaseName=DBName
username=username
password=userpwd
测试代码以下数据库
public class SqlserverTest {
public static void main(String[] args) throws Exception {
// 建立链接
Connection con = null;
try {
con = SqlUtils.getConnection();
System.out.println("SQL数据库连接ok!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQL数据库连接失败!");
}
try {
SqlUtils.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
}