출처 : http://www.java2s.com/Code/Java/Database-SQL-JDBC/GetColumnNamesFromResultSetforMySQL.htm
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class GetColumnNamesFromResultSet_MySQL {
public static Connection getConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/databaseName";
String username = "root";
String password = "root";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void getColumnNames(ResultSet rs) throws SQLException {
if (rs == null) {
return;
}
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
// get the column names; column indexes start from 1
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
// Get the name of the column's table name
String tableName = rsMetaData.getTableName(i);
System.out.println("column name=" + columnName + " table=" + tableName + "");
}
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
// prepare query
String query = "select id, name, age from employees";
// create a statement
stmt = conn.createStatement();
// execute query and return result as a ResultSet
rs = stmt.executeQuery(query);
// get the column names from the ResultSet
getColumnNames(rs);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
'Programming > JAVA' 카테고리의 다른 글
Make a Java Daemon with Jsvc on Linux (0) | 2015.06.05 |
---|---|
Java Data Structure (0) | 2015.01.29 |
Open JDK와 Oracle JDK 차이 (0) | 2014.09.03 |
java oracle 설치 (0) | 2014.08.18 |
System OS Check (0) | 2014.08.18 |