java—将jdbc的输出格式化为表

u1ehiz5o  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(435)

这个问题在这里已经有答案了

如何用java打印信息表(4个答案)
上个月关门了。
我需要把数据库的输出打印成一个表

public static void main(String[] args) {

    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/walmart?characterEncoding=utf8","root","toor"); 

        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from salesperson"); 
        System.out.println(" Employee ID "+" Employee Name "+" Contact "+" Region "+"Sales");  
        while(rs.next())  
            System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3)+"  "+rs.getString(4)+"  "+rs.getFloat(5));  

        //step5 close the connection object  
        con.close();  
    }

    catch(Exception e){ System.out.println(e);}

} }

mitkmikd

mitkmikd1#

这是未经测试的快速方法code:-

ResultSet rs = statement.executeQuery();
   ResultSetMetaData rsmd = rs.getMetaData();
   int columnsCount = rsmd.getColumnCount();
   for (int i = 1; i <= columnsCount; i++) {
              if (i > 1) {
                System.out.print(",  ");
              }
              System.out.print(rsmd.getColumnName(i));
       }

   while (rs.next()) {
       for (int i = 1; i <= columnsCount; i++) {
           if (i > 1) {
            System.out.print(",  ");
           }
           String columnValue = rs.getString(i);
           System.out.print(columnValue);
       }
       System.out.println("");
   }

相关问题