1.下载连接引擎jar
微软官方:https://www.microsoft.com/en-us/download/details.aspx?id=11774
2.载入引擎
注意: 不同版本的引擎driver地址不一样
static final String SQLSERVER_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 初始化时调用一次
Class.forName(DBUtils.SQLSERVER_DRIVER);
3.建立数据库链接
static final String SQLSERVER_URL = "jdbc:sqlserver://192.168.1.1:1111;databaseName=xxxx";
static final String USER = "user_";
static final String PASSWORD = "password_";
// 获得数据库连接
Connection conn = DriverManager.getConnection(DBUtils.SQLSERVER_URL + dbName, DBUtils.USER, DBUtils.PASSWORD);
4.执行具体的操作
进行简单的查询操作
/**
* 查询公用方法
*
* @param conn 数据库连接
* @param sql 查询sql
* @param objects sql中的参数
* @author fengzhen
* @version v1.0, 2017/9/4 14:05
*/
public static List<Map<String, Object>> query(Connection conn, String sql, Object[] objects)
throws SQLException, ClassNotFoundException {
if (conn == null || sql == null) return null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
pstmt = conn.prepareStatement(sql);
for (int i = 1, j = objects.length; i <= j; i++) {
pstmt.setObject(i, objects[i - 1]);
}
resultSet = pstmt.executeQuery();
return DBUtils.resultToList(resultSet);
} finally {
DBUtils.close(conn, resultSet, pstmt);
}
}
/**
* 查询结果转换为List
*
* @author fengzhen
* @version v1.0, 2017/9/4 15:10
*/
public static List<Map<String, Object>> resultToList(ResultSet resultSet)
throws SQLException {
ArrayList<Map<String, Object>> result = new ArrayList<>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
HashMap<String, Object> map = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
map.put(metaData.getColumnName(i), resultSet.getString(i));
}
result.add(map);
}
return result;
}
/**
* 释放链接
*
* @author fengzhen
* @version v1.0, 2017/9/4 14:59
*/
public static void close(Connection conn, ResultSet rs, PreparedStatement ps)
throws SQLException {
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
if (conn != null) {
conn.close();
}
}