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(); } } }
  • 相关阅读:
    git把dev部分提交过的内容合并到master
    shell命令修改文件内容
    js时间格式化
    js判断对象是否为空
    JS数组遍历方法
    批量修改文件后缀
    curl实现put请求
    lumen伪静态路由设置示例
    nginx client_body_buffer_size
    nginx模块开发
  • 原文地址:https://www.cnblogs.com/llsq/p/7744779.html
Copyright © 2011-2022 走看看