zoukankan      html  css  js  c++  java
  • 用JDBC获得元数据

    在查询一个未知的表时,我们不知道表中有多少列,这些列都是什么类型,可以通过查询元数据,查询他的列数、列名、列的类型。

    代码:

    package jdbc_preparement;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class text_preparestartment {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
          Connection con=simplecon.getConnection();
          String sql="select * from t_user";
         try {
             simple.getGeneral(sql);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        }
    
    }
    //连接数据库
    class simplecon { static Connection con; static Connection getConnection() { try{ con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","数据库名","数据库密码"); }catch(SQLException e){ e.printStackTrace(); } return con; } static void close(AutoCloseable a) { try { a.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }class simple { static void getGeneral(String sql) { Connection con=simplecon.getConnection(); try { PreparedStatement ps=con.prepareStatement(sql); ResultSetMetaData re=ps.getMetaData(); //获得元数据 int count=re.getColumnCount(); //返回列数 for(int i=1;i<=count;i++) //返回列类型 { System.out.print(re.getColumnTypeName(i)+" "); } System.out.println(); for(int i=1;i<=count;i++) //返回列名 { System.out.print(re.getColumnLabel(i)+" "); } System.out.println(); //执行sql查询 ResultSet re2=ps.executeQuery(); //返回查询结果 while(re2.next()) { for(int i=1;i<=count;i++) { System.out.print(re2.getString(i)+" "); } System.out.println(); } simplecon.close(ps); simplecon.close(re2); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
  • 相关阅读:
    BFC
    js异常处理
    vue双向数据绑定的简单实现
    cookie封装,localstage封装
    问题 1476: [蓝桥杯][基础练习VIP]龟兔赛跑预测 (模拟)
    HDU 6205 (模拟) card card card
    HDU 4545 (模拟) 魔法串
    HDU 4521 小明系列问题——小明序列 (线段树 单点更新)
    基础动态规划 讲解
    HDU 1561 The more, The Better (有依赖背包 || 树形DP)
  • 原文地址:https://www.cnblogs.com/llsq/p/7744779.html
Copyright © 2011-2022 走看看