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(); } } }
  • 相关阅读:
    [YTU]_2436( C++ 习题 输出日期时间--友元类)
    [YTU]_2435 ( C++ 习题 输出日期时间--友元函数)
    病毒侵袭
    石子合并(区间DP经典例题)
    AC自动机模板2
    【模板】最近公共祖先(LCA)
    华华给月月出题
    线性筛素数
    华华开始学信息学
    华华和月月种树
  • 原文地址:https://www.cnblogs.com/llsq/p/7744779.html
Copyright © 2011-2022 走看看