java Web连接MySQL数据库工具类 实现分组查询取组最后一条数据

来源:互联网 发布:数码兽传说:网络侦探 编辑:程序博客网 时间:2024/05/18 07:28

代码:如下:
public class DBConnection {private static String DBurl ="jdbc:mysql://localhost:3306/mMysqlDB?user=root&password=root&useUnicode=true&characterEncoding=utf-8" ;//myDB为数据库名 private static Connection Connect = null;/** * 获取数据库连接 * @author lcg * @date 2014年9月24日11:48:49 * @return java.sql.Connection; */public static Connection getConnection(){//com.mysql.jdbc.Drivertry {Class.forName("com.mysql.jdbc.Driver").newInstance();} catch (InstantiationException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IllegalAccessException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (ClassNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} try {Connect = DriverManager.getConnection(DBurl);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} return Connect;}/** * 获取创建数据库连接状态 * @author lcg * @date 2014年9月24日11:48:49 * @return java.sql.Statement; */public static Statement getStatement(){Statement state = null;try {state =  DBConnection.getConnection().createStatement();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} return state;}/** * 获取创建数据库连接状态 * @author lcg * @date 2014年9月24日11:48:49 * @return java.sql.Statement; */public static void  closeConnection(){if(Connect != null){try {Connect.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

分组查询取最新数据用法如下:

String softUsageSQL = "SELECT a.id,a.region_id,a.region_name ,a.tv_version "+"FROM (select * FROM tv_system_device_data WHERE region_id != '53' ORDER BY id DESC ) a "+" GROUP BY a.region_id ORDER BY a.id";ResultSet resultset = null;int nAllSize = 0;try {resultset = DBConnection.getStatement().executeQuery(softUsageSQL);while(resultset.next()){String strtemp = ""+resultset.getString("tv_version");}} catch (SQLException e) {e.printStackTrace();}DBConnection.closeConnection();





0 0
原创粉丝点击