I am facing error java.sql.SQLFeatureNotSupportedException in my prepare statement. I am using Mysql database.
Below is my code.
class tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
PreparedStatement pst = conn
.prepareStatement("select * from userinfo where firstname in(?)");
String[] Parameter = { "user1", "Administrator" };
Array sqlArray = conn.createArrayOf("VARCHAR", Parameter);
pst.setArray(1, sqlArray);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
For Mysql -
Setting array is not possible in Mysql.
Instead of that you can form a query for (?,?,..) in the loop and same way for setting values.
String[] Parameter = { "user1", "Administrator" };
String query = "select * from userinfo where firstname in (";
String temp = "";
for(i = 0; i < Parameter.length; i++) {
temp += ",?";
}
temp = temp.replaceFirst(",", "");
temp += ")";
query = query + temp;
PreparedStatement pst = conn.prepareStatement(query);
so query becomes
select * from userinfo where firstname in (?,?)
and pass values also using loop.
For Oracle -
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CHAR_ARRAY", conn);
String[] Parameter = { "user1", "Administrator" };
java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, conn, content);
.
.
pstmt.setArray(1, sqlArray);
Error message is very clear. And MySQL does not support custom data types.
Currently MySQL is supporting only:
Numeric Type
Date and Time Type
String Type
Or, you can use each of the input values as a set of values of IN function in MySQL.
Change your JAVA code as follows:
StringBuilder sbSql = new StringBuilder( 1024 );
sbSql.append( "select * from userinfo where firstname in(" );
for( int i=0; i < Parameter.length; i++ ) {
if( i > 0 ) sbSql.append( "," );
sbSql.append( " ?" );
} // for
sbSql.append( " )" );
PreparedStatement pst = conn.prepareStatement( sbSql.toString() );
for( int i=0; i < Parameter.length; i++ ) {
pst.setString( i+1, Parameter[ i ] );
} // for
ResultSet rs = pst.executeQuery();
Convert List to a comma separated String and use it.
Class Tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
// Consider this list is already constructed
List<String> parameter = new ArrayList<String>();
parameter.add("user1");
parameter.add("Administrator");
String parameterStr = "'" + String.join("','", parameter) + "'";
PreparedStatement pst = conn.prepareStatement("select * from userinfo where firstname in(" + parameterStr + ")");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I've read H2 docs about storing objects in database. There is special SQL type OTHER and methods setObject and getObject. I've tried this code:
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("CREATE TABLE PUBLIC.foo (name VARCHAR(64) NOT NULL, data OTHER NULL);");
statement.execute();
} finally {
statement.close();
}
statement = null;
try {
statement = connection.prepareStatement("INSERT INTO PUBLIC.foo (name, data) VALUES(?,?);");
statement.setString(1, "lololo");
statement.setObject(2, new String[]{"foo", "bar"});
statement.execute();
}finally {
statement.close();
}
But I've got the exception:
org.h2.jdbc.JdbcSQLException: Ше�тнадцатирична� �трока �одержит неше�тнадцатиричные �имволы: "(foo, bar)"
Hexadecimal string contains non-hex character: "(foo, bar)"; SQL statement:
INSERT INTO PUBLIC.foo (name, data) VALUES(?,?) -- (?1, ?2) [90004-191]
What is wrong?
I believe this is what you were look for (Even I was).
You just need to create a column in your table with type as 'other'.
See 'create table testobj2(obj other)'
Look at my Sample code :
static String DB_DRIVER = "org.h2.Driver";
static String DB_CONNECTION = "jdbc:h2:./test2";
static String DB_USER = "";
static String DB_PASSWORD = "";
public static void benchmarkH2Inserts() {
try {
Class.forName(DB_DRIVER);
Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
String createQry = "create table testobj2(obj other)";
String insertQuery = "insert into testobj2(obj) values(?)";
String selectQuery = "select * from testobj2";
// dbConnection.setAutoCommit(false);
dbConnection.prepareStatement(createQry).executeUpdate();
long lStartTime = System.nanoTime();
for(int i=0; i<10000; i++) {
dbConnection.setAutoCommit(false);
CloudElement_Circuit obj = new CloudElement_Circuit();
obj.setNrm8DesignId(1230L);
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertQuery);
preparedStatement.setObject(1,obj);
preparedStatement.execute();
dbConnection.commit();
}
long lEndTime = System.nanoTime();
long output = lEndTime - lStartTime;
System.out.println("benchmarkH2Inserts() : Elapsed time in nanoseconds: " + output);
System.out.println("benchmarkH2Inserts() : Elapsed time in milliseconds: " + output / 1000000);
//Selecting
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectQuery);
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
CloudElement_Circuit obj = (CloudElement_Circuit) rs.getObject("obj");
System.out.println("Fetched Object : " + obj.getNrm8DesignId());
}
dbConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note that 'CloudElement_Circuit' is a Serialized class.
Look at 'OTHER Type' here : http://www.h2database.com/html/datatypes.html
H2 Example : https://www.javatips.net/blog/h2-database-example
Try this approach
List<String> genre = new ArrayList<String>();
String comma="";
StringBuilder allGenres = new StringBuilder();
for (String g: genre) {
allGenres.append(comma);
allGenres.append(g);
comma = ", ";
}
Then you can pass it like this
preparedStmt.setString (2, allGenres.toString());
This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 6 years ago.
I am trying to run following code but getting error:
SQL Exception thrown: java.sql.SQLException: Operation not allowed
after ResultSet closed.
How to resolve this error? I need two result sets for my application.
public static void main(String[] args) {
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/test";
String dbUser = "root";
String dbPwd = "Syntel#92";
Connection conn;
ResultSet rs, res1 = null;
Statement stmt = null;
int rowcount = 0;
// String queryString = "create table job_status_table as select j1.job_id,s1.Source_ID,s1.Source_name from JOb_list j1,SOURCE_DETAILS s1 where s1.Source_ID = j1.Source_ID";
String queryString = "create table job_status_table as select source_id,source_name from source_details";
String addcolumn = "alter table job_status_table add column Source_rowcount int";
String fetchdata = "Select Source_name from job_status_table";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
stmt = conn.createStatement();
// get record count from table job_status_table1
// stmt.executeQuery("select count() from job_status_table1");
// create table
stmt.executeUpdate(queryString);
System.out.println("Table created in the database");
stmt.executeUpdate(addcolumn);
System.out.println("alter table");
rs = stmt.executeQuery(fetchdata);
System.out.println("fetch data");
while (rs.next()) {
String table_count = null;
String table_name = null;
table_name = rs.getString("Source_name");
System.out.println(table_name);
// table_name = rs.getString("Source_name");
//System.out.println(table_name);
//rs.close();
table_count = "select count(*) from " + table_name;
//table_count = "select count(*) from " + table_name;
//rs.close();
// res1 = stmt.executeQuery(table_count);
res1 = stmt.executeQuery(table_count);
//System.out.print(res1);
if (res1.next()) {
rowcount = res1.getInt(1);//res1.getInt(1);
System.out.println("Result set values" + rowcount);
} else {
System.out.println("value is not present in resultset");
}
System.out.println("Get Row Count");
System.out.println(table_count);
// int cnt = rcnt(table_count);
String updaterow = "update job_status_table set Source_rowcount ="
+ rowcount
+ " where Source_name = '"
+ table_name
+ "'";
System.out.println("updateoutput" +stmt.executeUpdate(updaterow));
System.out.println("Update Complete");
}
/* if (conn != null) {
rs.close();
res1.close();
stmt.close();
conn.close();
conn = null;
}
*/
}
catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}**
You could try this:
First copy the ResultSet rs in an ArrayList and close it.
Iterate over the ArrayList and close res1 before the update.
And I don't think the else with "value is not present in resultset" is reachable, but if you should set the rowcount to 0.
EDIT
After reading the referenced question the second time:
The problem is the reusing of stmt for res1 and the update
I'm a MySQL user and I have been using following statements in MySQL Workbench :
(these statements are based on Select column names whose entries are not null)
SET group_concat_max_len = 4294967295;
SELECT GROUP_CONCAT(
' SELECT ',QUOTE(COLUMN_NAME),
' FROM ( select * from table_name where s3_01 = ', coloumn1,' ) abc',
' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL',
' HAVING COUNT(*)'
SEPARATOR ' UNION ALL ')
INTO #sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'table_name';
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Although it work in my workbench, I do not know how to make it work in java.
for example, I made following code:
String sql1 = "SET group_concat_max_len = 4294967295;";
String sql2 = " SELECT GROUP_CONCAT(' SELECT ',QUOTE(COLUMN_NAME), ' FROM ( select * from ptc_weight where s3_01 = ',column1,' ) abc', ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL', ' HAVING COUNT(*)' SEPARATOR ' UNION ALL ') INTO #sql FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'ptc_weight'; ";
String sql3 = " PREPARE stmt FROM #sql; ";
String sql4 = " EXECUTE stmt;";
String sql5 = " DEALLOCATE PREPARE stmt;";
String[] result = getResult(sql1+sql2+sql3+sql4+sql5);
public static String[][] getResult(String sql) {
System.out.println(sql);
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String[][] resultTable = null;
try {
con = getCon();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData result = rs.getMetaData();
int rowNum=0;
// Go to the last row
rs.last();
rowNum = rs.getRow();
// Reset row before iterating to get data
rs.beforeFirst();
int colNum = result.getColumnCount();
resultTable = new String[rowNum][colNum];
for(int itr1=0; itr1<rowNum; itr1++){
rs.next();
for(int itr2=0; itr2<colNum; itr2++){
resultTable[itr1][itr2] = rs.getObject(itr2+1).toString();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
dbclose(con, ps, rs);
}// finally
return resultTable;
}
However, it does not work. I guess I made a wrong code for utilizing stored procedure, but I don't have any idea to deal with this problem.
CallableStatement callableStatement = null;
String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);
// execute getDBUSERByUserId store procedure
callableStatement.executeUpdate();
String userName = callableStatement.getString(2);
String createdBy = callableStatement.getString(3);
Date createdDate = callableStatement.getDate(4);
System.out.println("UserName : " + userName);
System.out.println("CreatedBy : " + createdBy);
System.out.println("CreatedDate : " + createdDate);
Here Is Full Example. You can modify your code as you need.
Simple one with less argument and with resultset :
CallableStatement cstmt = con.prepareCall("{call getEmployeeDetails(?, ?)}");
cstmt.setInt("employeeId", 123);
cstmt.setInt("companyId", 456);
ResultSet rs = cstmt.executeQuery();
I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.
You can get this info from the ResultSet metadata. See ResultSetMetaData
e.g.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);
and you can get the column name from there. If you do
select x as y from table
then rsmd.getColumnLabel() will get you the retrieved label name too.
In addition to the above answers, if you're working with a dynamic query and you want the column names but do not know how many columns there are, you can use the ResultSetMetaData object to get the number of columns first and then cycle through them.
Amending Brian's code:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
This question is old and so are the correct previous answers. But what I was looking for when I found this topic was something like this solution. Hopefully it helps someone.
// Loading required libraries
import java.util.*;
import java.sql.*;
public class MySQLExample {
public void run(String sql) {
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost/demo";
// Database credentials
String USER = "someuser"; // Fake of course.
String PASS = "somepass"; // This too!
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
Vector<String> columnNames = new Vector<String>();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
System.out.print(columns.getColumnName(i) + "\t");
columnNames.add(columns.getColumnName(i));
}
System.out.print("\n");
while (rs.next()) {
for (i = 0; i < columnNames.size(); i++) {
System.out.print(rs.getString(columnNames.get(i))
+ "\t");
}
System.out.print("\n");
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception mysqlEx) {
System.out.println(mysqlEx.toString());
}
}
}
}
SQLite 3
Using getMetaData();
DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);
System.out.println("your_table_name");
while (rset.next())
{
System.out.println("\t" + rset.getString(4));
}
EDIT: This works with PostgreSQL as well
import java.sql.*;
public class JdbcGetColumnNames {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/komal", "root", "root");
st = con.createStatement();
String sql = "select * from person";
rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " + metaData.getTableName(2));
System.out.println("Field \tDataType");
for (int i = 0; i < rowCount; i++) {
System.out.print(metaData.getColumnName(i + 1) + " \t");
System.out.println(metaData.getColumnTypeName(i + 1));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Table Name : person
Field DataType
id VARCHAR
cname VARCHAR
dob DATE
while (rs.next()) {
for (int j = 1; j < columncount; j++) {
System.out.println( rsd.getColumnName(j) + "::" + rs.getString(j));
}
}
When you need the column names, but do not want to grab entries:
PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");
ResultSet set = stmt.executeQuery();
//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }
NOTE: Only works with MySQL
The SQL statements that read data from a database query return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The **java.sql.ResultSet** interface represents the result set of a database query.
Get methods: used to view the data in the columns of the current row
being pointed to by the cursor.
Using MetaData of a result set to fetch the exact column count
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html
and further more to bind it to data model table
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
}//end try
System.out.println("Goodbye!");
}//end main
//end JDBCExample
very nice tutorial here : http://www.tutorialspoint.com/jdbc/
ResultSetMetaData meta = resultset.getMetaData(); // for a valid resultset object after executing query
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = null;
while(columncount <=count) {
columnNames [i] = meta.getColumnName(i);
}
System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);
#Cyntech is right.
Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Vector<Vector<String>>tableVector = new Vector<Vector<String>>();
boolean isTableEmpty = true;
int col = 0;
while(rs.next())
{
isTableEmpty = false; //set to false since rs.next has data: this means the table is not empty
if(col != columnCount)
{
for(int x = 1;x <= columnCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
col = columnCount;
}
}
//if table is empty then get column names only
if(isTableEmpty){
for(int x=1;x<=colCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
}
rs.close();
stmt.close();
return tableVector;
ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery();
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1
String nameValuePair = "";
while (rsTst.next()) {
for (int i = 1; i < columnCount + 1; i++ ) {
String name = meta.getColumnName(i);
// Do stuff with name
String value = rsTst.getString(i); //.getObject(1);
nameValuePair = nameValuePair + name + "=" +value + ",";
//nameValuePair = nameValuePair + ", ";
}
nameValuePair = nameValuePair+"||" + "\t";
}
If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:
jdbcTemplate.query("select * from books", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
}
});
U can get column name and value from resultSet.getMetaData();
This code work for me:
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = MySQLJDBCUtil.getConnection();
preparedStatement = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
while (resultSet.next()) {
int counter = md.getColumnCount();
String colName[] = new String[counter];
Map<String, Object> field = new HashMap<>();
for (int loop = 1; loop <= counter; loop++) {
int index = loop - 1;
colName[index] = md.getColumnLabel(loop);
field.put(colName[index], resultSet.getObject(colName[index]));
}
rows.add(field);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return rows;
I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData by label instead of index:
ResultSet resultSet = null;
DatabaseMetaData metaData = null;
try {
metaData = connection.getMetaData();
resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()){
String name = resultSet.getString("COLUMN_NAME");
}
}