If you run a select query where the number of columns and their data types are unknown, you may generate different numbers of columns and rows from the populated result-set.
Download the required jar file, mysql-connector with revision number and add it to your project library.
Download the required jar file, mysql-connector with revision number and add it to your project library.
package com.ba.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class TestMain {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/dbname", "username", "password");
PreparedStatement pStatement = connection
.prepareStatement("select * from userstab");
ResultSet rs = pStatement.executeQuery();
ResultSetMetaData rSetMetaData = rs.getMetaData();
int colCount = rSetMetaData.getColumnCount();
System.out.println("Columns are: ");
for (int c = 1; c <= colCount; c++) {
System.out.print(" " + rSetMetaData.getColumnName(c));
System.out.print(" " + rSetMetaData.getColumnDisplaySize(c));
System.out.print(" " + rSetMetaData.getColumnTypeName(c));
System.out.println();
}
while (rs.next()) {
for (int c = 1; c <= colCount; c++) {
if (rSetMetaData.getColumnTypeName(c).equalsIgnoreCase(
"VARCHAR")) {
System.out.print(" " + rs.getString(c));
} else if (rSetMetaData.getColumnTypeName(c)
.equalsIgnoreCase("NUMBER")) {
System.out.print(" " + rs.getInt(c));
} else {
// ......
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.