数据库连接——SQLServer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38137589/article/details/85053170
   private static Logger logger = Logger.getLogger(Test.class);
   //驱动
   private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    // 连接路径
    private static final String URL = "jdbc:sqlserver://XXX:1433;databaseName=XXX";
    // 用户名
    private static final String USERNAME = "";
    // 密码
    private static final String PASSWORD = "";
     
    //静态代码块
    static {
        try {
            // 加载驱动
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    /*
     * 获取数据库连接
     */
    public static Connection getConnection() {
        Connection conn = null;
        logger.info("开始连接数据库");
        try{
            conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }catch(SQLException e){
            e.printStackTrace();
            logger.error("数据库连接失败!");
        }
        logger.info("数据库连接成功");
        return conn;
    }
 
    /*
     * 关闭数据库连接,注意关闭的顺序
     */
    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        if(rs!=null){
            try{
                rs.close();
                rs=null;
            }catch(SQLException e){
                e.printStackTrace();
                logger.error("关闭ResultSet失败");
            }
        }
        if(ps!=null){
            try{
                ps.close();
                ps=null;
            }catch(SQLException e){
                e.printStackTrace();
                logger.error("关闭PreparedStatement失败");
            }
        }
        if(conn!=null){
            try{
                conn.close();
                conn=null;
            }catch(SQLException e){
                e.printStackTrace();
                logger.error("关闭Connection失败");
            }
        }
    }
    //测试数据库连接是否成功
    public static String getInfo() throws Exception {
		Connection conn =null;
		Statement st=null;
		ResultSet rs = null;
		String sql = "select productType ,id from 表名";
		JSONArray js = new JSONArray();
		try {
			conn = getConnection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			String productType = "";
			while (rs.next()) {
				JSONObject object = new JSONObject();
				productType = rs.getString("productType");
				object.put("productType", productType);
				js.put(object);
			}
		} catch (Exception e) {
			sql="ERR: "+e.toString();
			e.printStackTrace();
		} finally {
			if (st!=null) st.close();
			if (rs!=null) rs.close();
			if (conn!=null)  close(null,null,conn);
		}
		return js.toString();		
	}

猜你喜欢

转载自blog.csdn.net/m0_38137589/article/details/85053170