标签:span get sql查询 blog blob logs tar closeable pack
在查询一个未知的表时,我们不知道表中有多少列,这些列都是什么类型,可以通过查询元数据,查询他的列数、列名、列的类型。
代码:
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(); } } }
标签:span get sql查询 blog blob logs tar closeable pack
原文地址:http://www.cnblogs.com/llsq/p/7744779.html