MySQL表在Java里面遍历,以获取ResultSet行数列数的方式

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Emp {
    private ResultSet rs;
    private Connection connection;
    private Statement statement;
    private ResultSetMetaData rsmd;

    public static Emp getEmp(String url, String user, String password) {
        Emp emp = new Emp();
        try {
            //Class.forName("com.mysql.cj.jdbc.Driver");//可以不用写 MySQL.jar里面自带配置文件
            emp.connection = DriverManager.getConnection(url, user, password);//获取数据库链接
            emp.statement = emp.connection.createStatement();//获取执行者对象
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return emp;
    }

    private Emp() {
    }

    public void setResultSet(String sql) throws SQLException {
        rs = statement.executeQuery("select * from "+sql+";");
        //rs = statement.executeQuery(sql);
    }

    public void findAll(Emp e, String sql) {  //遍历ResultSet对象并打印在控制台
        try {
            e.setResultSet(sql);
            e.setResultSetMetaData();//更新获得ResultSetMetaData
            int columnCount = e.getColumns();
            for (int i = 1; i <= columnCount; i++) {
                if (i == columnCount) {
                    System.out.println(rsmd.getColumnName(i));
                } else {
                    System.out.print(rsmd.getColumnName(i)+",");
                }
            }
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    String string = rs.getString(i);
                    if (i == columnCount) {
                        System.out.println(string);
                    } else {
                        System.out.print(string + ",");
                    }
                }
                System.out.println();
            }
        } catch (SQLException t) {
            t.printStackTrace();
        }
    }

    private void setResultSetMetaData() throws SQLException {
        rsmd= rs.getMetaData();
    }


    private int getColumns() throws SQLException { //检索获取此 ResultSet对象里(列的数量,类型和属性)信息的对象。  返回此 ResultSet对象中的列数。
        return rsmd.getColumnCount();
    }

    public List<String> toList(Emp e, String table) {  //遍历表的每一行,以逗号","分割获取每一行中每一列的信息转为字符串并添加到list集合返回
        List<String> list = new ArrayList<>();
        try {
            e.setResultSet(table);
            int columnCount = e.getColumns();
            while (rs.next()) {
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= columnCount; i++) {
                    String string = rs.getString(i);
                    if (i == columnCount) {
                        sb.append(string);
                    } else {
                        sb.append(string).append(",");
                    }
                }
                list.add(sb.toString());
            }
        } catch (SQLException t) {
            t.printStackTrace();
        }
        return list;
    }

    public void toClose(Emp emp){ //清空资源  目前不清楚内存资源的机制 "未被声明的变量接收的对象在执行语句完毕后是否任然会占用内存资源"
        if (emp.statement != null) {
            try {
                emp.statement.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (emp.connection != null) {
            try {
                emp.connection.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (emp.rs != null) {
            try {
                emp.rs.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
    }

    public int toUpdate(String table,String set,String where) throws SQLException { //
        //"update emp set age = 22 where id =1;";
        return statement.executeUpdate("update "+table+"set "+set+" where "+where+";");
    }

    public int toCreate(String sql) throws SQLException { //

        return statement.executeUpdate(sql);
    }
}

最开始是想遍历来着然后为了好看编了找了一下方法,为了输出格式好看点就没考虑采用转list集合遍历,然后想要格式化我就想到跟wps表格一样来一行一行一列一列顺位遍历格式。

这就得考虑到事先是很难提前知道表的列数行数列名还有数据类型,但想了想反正就只是看和控制台打印就全用string来接受数据类容。然后是行数列数,因为为了格式好看放弃了集合遍历,就没办法增强for遍历了,这就得想办法了获取ResultSet对象列数和行数,或者有其他方法限制行的遍历,然后我在api里面找到了这个

    • next()

      将光标从当前位置向前移动一行。

        •       throws SQLException
          将光标从当前位置向前移动一行。 ResultSet光标最初位于第一行之前; 第一次调用方法next使第一行成为当前行; 第二个调用使第二行成为当前行,依此类推。

          当调用next方法返回false时,光标位于最后一行之后。 任何调用需要当前行的ResultSet方法将导致抛出SQLException 。 如果结果集类型为TYPE_FORWARD_ONLY ,这是他们指定的JDBC驱动程序实现是否会返回供应商false或抛出一个SQLException上的后续调用next

          如果当前行的输入流已打开,则对方法next的调用将隐式关闭它。 当读取新行时, ResultSet对象的警告链将被清除。

          结果

          true如果新的当前行有效; false如果没有更多的行

          异常

          SQLException - 如果发生数据库访问错误,或者在关闭的结果集上调用此方法

这就解决了遍历行的操作限制,然后就是列的问题,我看到了最后一个方法
    • wasNull()

        •          throws SQLException

          报告最后一列读取的值是否为SQL NULL 。 请注意,您必须先在列上调用其中一个getter方法以尝试读取其值,然后调用方法wasNull来查看读取的值是否为SQL NULL

          结果

          true如果读取的最后一列值为SQL NULLfalse false

          异常

          SQLException - 如果发生数据库访问错误或在关闭的结果集上调用此方法

由于并不确定ResultSet对象是否有横向光标就先用该方法做判断
结果是因为理解错了判断,
while (rs.next()){
                int i = 1;
                while (rs.isLast()){
                    String string = rs.getString(i);
                    System.out.print(string+",");
                    i++;
                }
                System.out.println();
            }
所以只能另想办法

在社区里面找了一圈没看到有办法获取ResultSet对象的列数 ,然后没办法去帮助文档里面找了一下,发现api并没有直接提供获取列的个数的方法,但是找到了这个方法

这个接口提供了一个方法

    • getColumnCount()

      返回此 ResultSet对象中的列数。

        • int getColumnCount()
                      throws SQLException

          返回此 ResultSet对象中的列数。

          结果

          列数

          异常

          SQLException - 如果发生数据库访问错误

这就有了列数,就好操作了。

这个类还提供了一个方法

这样列名就有了

还有一个获得表名的方法我就不加了。

最新版本

package com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class JDBCUtils5 {
    public static String url;
    private static String username;
    private static String password;
    //private static String driver;
    private static String table;
    private static String set;
    private static String where;
    private static boolean a;

    private static Connection conn;//数据库链接
    private static Statement sm;//数据执行对象
    private static ResultSet rs;//
    private static ResultSetMetaData RSM;//表的数据集合对象
    private static DataSource ds;//数据源
    private static PreparedStatement PST;//站位符对象
    private static JdbcTemplate JT;//

    static {
        try {
            Properties pp = new Properties();
            //pp.load(new FileReader("jdbc.properties"));
            pp.load(JDBCUtils5.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            table = pp.getProperty("table");
            set =pp.getProperty("set");
            where = pp.getProperty("where");

            Properties pp2 = new Properties();
            //pp2.load(new FileReader("druid.properties"));
            pp2.load(JDBCUtils5.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pp2);
            username = pp2.getProperty("username");
            password = pp2.getProperty("password");
            url = pp2.getProperty("url");
        } catch (Exception ioException) {
            ioException.printStackTrace();
        }
    }

    public static JDBCUtils5 getUtils(){
        JDBCUtils5 ju = new JDBCUtils5();
        try {
            ju.setConn(ds);
            ju.setJT(ds);
        } catch (Exception t) {
            t.printStackTrace();
        }
        return ju;
    }

    public void setA(boolean a1) {
        a = a1;
    }

    public int UpdateStart(String sql){//JdbcTemplate对象执行事务的update
        int i = -1;
        try {
            setA(false);
            conn.setAutoCommit(a);
            i = JTUpdate(sql);
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return i;
    }

    public int UpdateStart(){
        int i = 0;
        try {
            setA(false);
            conn.setAutoCommit(a);
            i = ExecuteUpdate();
        }catch (SQLException s){
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            s.printStackTrace();
        }
        return i;
    }

    public int UpdateStart(String sql,@Nullable  Object...args){//JdbcTemplate对象执行事务的update
        int i = -1;
        try {
            setA(false);
            conn.setAutoCommit(a);
            i = JTUpdate(sql, args);
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return i;
    }


    public Map<String, Object> QueryForMapStart(String sql){
        Map<String, Object> map = null;
        try {
            setA(false);
            conn.setAutoCommit(a);
            map = JT.queryForMap(sql);
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return map;
    }

    public Map<String, Object> QueryForMapStart(String sql,@Nullable Object...args){
        Map<String, Object> map = null;
        try {
            setA(false);
            conn.setAutoCommit(a);
            map = JT.queryForMap(sql,args);//方法结果集长度只能为1
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return map;
    }

    public List<Map<String, Object>> QueryForListStart(String sql){
        List<Map<String, Object>> list = null;
        try {
            setA(false);
            conn.setAutoCommit(a);
            list = JT.queryForList(sql);
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return list;
    }

    public List<Map<String, Object>> QueryForListStart(String sql,@Nullable Object...args){
        List<Map<String, Object>> list = null;
        try {
            setA(false);
            conn.setAutoCommit(a);
            list = JT.queryForList(sql, args);//方法结果集长度只能为1
        } catch (SQLException t) {
            try {
                if (conn!=null){
                    conn.rollback();
                }
            } catch (SQLException t1) {
                t1.printStackTrace();
            }
            t.printStackTrace();
        }
        return list;
    }

    public void end(boolean b){//关闭事务 true提交 false回卷
        if (a){
            System.out.println("事务尚未开启或已经关闭");
        }else {
            try {
                if (conn!=null){
                    if (b){
                        conn.commit();
                    }else {
                        conn.rollback();
                    }
                }
                setA(true);
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
    }

    public void setResultSet(){//查看表的全部
        try {
            PST = conn.prepareStatement("select * from "+table);
            rs =PST.executeQuery();
        } catch (SQLException t) {
            t.printStackTrace();
        }
    }

    public static void findAll(JDBCUtils5 ju) {  //遍历ResultSet对象并打印在控制台
        try {
            ju.setResultSet();
            ju.setResultSetMetaData();//更新获得ResultSetMetaData
            int columnCount = ju.getColumns();
            for (int i = 1; i <= columnCount; i++) {
                if (i == columnCount) {
                    System.out.println(RSM.getColumnName(i));
                } else {
                    System.out.print(RSM.getColumnName(i)+",");
                }
            }
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    String string = rs.getString(i);
                    if (i == columnCount) {
                        System.out.println(string);
                    } else {
                        System.out.print(string + ",");
                    }
                }
                System.out.println();
            }
        } catch (SQLException t) {
            t.printStackTrace();
        }
    }

    public boolean login(String username,String password){//判断登录账号
        if (username == null || password == null) {
            return false;
        }
        try {
            setResultSet3();
            return PST.executeQuery().next();
        } catch (SQLException t) {
            t.printStackTrace();
        }
        return false;
    }

    @Deprecated
    public int toUpdate() throws SQLException { //Update的sql语句执行
        //"update emp set age = 22 where id =1;";
        PST= conn.prepareStatement("update "+table+" set "+set+" where "+where+";");
        return PST.executeUpdate();
    }

    public void Close(){ //清空资源  目前不清楚内存资源的机制 "未被声明的变量接收的对象在执行语句完毕后是否任然会占用内存资源"
        if (sm != null) {
            try {
                sm.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException t) {
                t.printStackTrace();
            }
        }
        if (PST!=null){
            try {
                PST.close();
            }catch (SQLException t){
                t.printStackTrace();
            }
        }
    }

    public void ExecuteQuery() throws SQLException {
        PST.executeQuery();
    }

    public int ExecuteUpdate() throws SQLException {
        return PST.executeUpdate();
    }

    /*public void JTQuery(String sql){
        JT.query(sql,);
    }*/

    public int JTUpdate(String sql){
        return JT.update(sql);
    }

    public int JTUpdate(String sql,Object...args){
        return JT.update(sql,args);
    }

    /*public void JTQuery(String sql,Object o){
        JT.query(sql, new RowMapper<Object>() {
            @Override
            public Object mapRow(ResultSet rs, int i) throws SQLException {
                return null;
            }
        });
    }*/

    public void setResultSet3() throws SQLException{//根据where查看表数据
        PST = conn.prepareStatement("select * from "+table+" where username = ? and password = ?");
        PST.setString(1, JDBCUtils5.username);
        PST.setString(2, JDBCUtils5.password);


        rs =PST.executeQuery();
        PST.executeUpdate();
    }

    private void setResultSetMetaData() throws SQLException {
        RSM= rs.getMetaData();
    }

    private int getColumns() throws SQLException { //检索获取此 ResultSet对象里(列的数量,类型和属性)信息的对象。  返回此 ResultSet对象中的列数。
        return RSM.getColumnCount();
    }

    private JDBCUtils5() {
    }

    public ResultSet getRs() {
        return rs;
    }

    public void setRs() throws SQLException{
        PST = conn.prepareStatement("select * from "+table);
        rs =PST.executeQuery();
    }

    public Connection getConn(String username,String password) throws SQLException {
        return ds.getConnection(username,password);
    }

    public void setConn(String url,String username,String password) throws SQLException{
        conn = DriverManager.getConnection(url, username, password);
    }

    private void setConn(DataSource ds) throws SQLException{
        //conn = ds.getConnection(username,password);
        conn = ds.getConnection();
    }

    public Statement getSm() {
        return sm;
    }

    public void setSm() throws SQLException {
        sm = conn.createStatement();
    }

    public PreparedStatement getPST() {
        return PST;
    }

    public void setPST(String sql) throws SQLException {
        PST = conn.prepareStatement(sql);
    }

    public void setPST(String sql,String...a){
        try {
            PST = conn.prepareStatement(sql);
            int i = 1;
            for (String s : a) {
                if (isNumeric(s)){
                    PST.setInt(i,Integer.parseInt(s));
                }else {
                    PST.setString(i,s);
                }
                i++;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public Connection getConn(){
        return conn;
    }

    public ResultSetMetaData getRSM() {
        return RSM;
    }

    public void setRSM() throws SQLException{
        RSM= rs.getMetaData();
    }

    public static DataSource getDs() {
        return ds;
    }

    private void setJT(DataSource ds) {
        JT= new JdbcTemplate(ds);
    }

    public JdbcTemplate getJT(){
        return JT;
    }

    public static boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值