Java链接sqlserver数据库工具类

直接上代码

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),配置文件内容如下:

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();
		}
	}
}

你可能感兴趣的:(Utils)