jdbc 连接
String jdbcParams ="{\n" + "\t\"DRIVER\": \"com.microsoft.sqlserver.jdbc.SQLServerDriver\",\n" + "\t\"URL\": \"jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test\",\n" + "\t\"USERNAME\": \"test\",\n" + "\t\"PASSWORD\": \"test\",\n" + "\t\"VIEWNAME\": \"test\"\n" + "}"; JSONObject object = JSONObject.parseObject(jdbcParams); String driverName = object.getString("DRIVER"); String url = object.getString("URL"); String userName = object.getString("USERNAME"); String passWord = object.getString("PASSWORD"); String viewTable = object.getString("VIEWNAME"); System.out.println("url: "+url+" driver: "+driverName); Connection con = null; PreparedStatement pst = null ; ResultSet rs = null; int count = 0; try { Class.forName(driverName); con = DriverManager.getConnection(url,userName,passWord); log.info("第三方数据库连接成功"); String sql = "SELECT COUNT(*) AS total FROM "+ viewTable +" WHERE name = ? AND code= ?"; pst = con.prepareStatement(sql); pst.setString(1,"dsfs"); pst.setString(2,"gfdgdf"); rs = pst.executeQuery(); while (rs.next()){ return rs.getInt("total"); } } catch (Exception e) { e.printStackTrace(); log.error("第三方数据库 url"+url+"连接失败!!"); } finally { this.close(rs,pst,con); }
/** * 关闭数据库连接,注意关闭的顺序 */ public void close(ResultSet rs,PreparedStatement pst,Connection con){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); log.error("关闭ResultSet失败!"); } } if (pst!=null){ try { pst.close(); } catch (SQLException e) { e.printStackTrace(); log.error("关闭PreparedStatement失败!"); } } if (con!=null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); log.error("关闭Connection失败!"); } } }