ResultSetMetaData 实例

DROP TABLE IF EXISTS `quart`;
CREATE TABLE `quart` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(21) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;

 

package com.app.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JdbcTest {
	private static ResultSet rs;
	private static ResultSetMetaData rsmd;
	private static DatabaseMetaData dma;
	private static Connection con;
	private static Statement stmt;
	public static void main(String[] args) throws Exception {
		String url = "jdbc:mysql://localhost:3306/test?characterEncoding=GBK";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, "root", "root");// 连接数据库
			//dma = con.getMetaData();// 获取数据库的元数据
			String sql="select * from  quart";
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			rsmd = rs.getMetaData();
			int columns = rsmd.getColumnCount();//一个多少个字段列名
			String rows = "";
			while(rs.next()){
				for (int i = 1; i <= columns; i++) {
					rows= rsmd.getColumnName(i);
					//System.out.println(rows);//字段名
					System.out.println(rs.getString(rows));
				}
			}
		} catch (Exception e) {
			System.err.println("query exception");
		} finally {
			rs.close();
		}
	}
}

 

你可能感兴趣的:(java,mysql)