1. 程式人生 > >使用jdbc操作sql server資料庫

使用jdbc操作sql server資料庫

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:sqlserver操作工具
 * @author:
 * @time:2016年5月4日 下午6:44:33
 */
public class SqlServerDBHelper {

	private static Connection conn = null;

	// 獲得連線物件
	public static Connection getConn() {
		String sDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String sDBUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=smsdb";
		String userName = "root"; // 預設使用者名稱
		String userPwd = "[ 6Liu.aDS]@!#51I"; // 密碼
		try {
			Class.forName(sDriverName);
			conn = DriverManager.getConnection(sDBUrl, userName, userPwd);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return conn;
	}

	// 關閉連線
	public static void closeConn(Statement statement) {
		try {
			statement.close();
			statement = null;
			conn.close();
			conn = null;
		} catch (Exception e) {
			e.printStackTrace();
			conn = null;
		}
	}

	// 獲得查詢結果集
	public static List<Map<String, Object>> queryList(String sql, Object[] params) {
		getConn();
		PreparedStatement ps = null;
		List<Map<String, Object>> resultList = null;
		try {
			ps = conn.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i + 1, params[i]);
				}
			}
			resultList = resultSetConvertList(ps.executeQuery());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		closeConn(ps);
		return resultList;
	}

	// 用於對錶的增刪改操作
	public static int update(String sql, Object[] params) {
		getConn();
		PreparedStatement ps = null;
		int updateResult = 0;
		try {
			ps = conn.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i + 1, params[i]);
				}
			}
			updateResult = ps.executeUpdate();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		closeConn(ps);
		return updateResult;
	}

	// ResultSet轉換成List<Map<String, Object>>
	private static List<Map<String, Object>> resultSetConvertList(ResultSet resultSet) throws SQLException {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		ResultSetMetaData rmd = resultSet.getMetaData();
		int columnCount = rmd.getColumnCount();
		while (resultSet.next()) {
			Map<String, Object> rowData = new HashMap<String, Object>();
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(rmd.getColumnName(i), resultSet.getObject(i));
			}
			list.add(rowData);
		}
		return list;
	}
}


 以上是程式碼,另外還需要依賴sqljdbc4.jar驅動包哦