Java - How to get Column name on Result Set [duplicate] - java

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
Hello I'm trying to make an error when there is no matched student...
and it will display like this
No matching records found and I want the column name still the same but still not figuring it out... can some one tell me if this is right??
Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname
public void SearchTableStudent() {
String tempSearchValue = searchStudent.getText().trim();
boolean empty = true;
sql = "SELECT student_id as 'Student ID',"
+ "concat(lastname, ' , ', firstname, ' ', middlename) as 'Name'"
+ "FROM user "
+ "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
empty = false;
}
if(empty) {
String error = "";
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"No matching records found",null}
},
new String [] {
/** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
WHAT FUNCTION TO DO*/
}
));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
I try like this but still gave me NULL!!!
this code is below of empty = false;
for(int i=0; i<table.getColumnCount(); i++) {
test[i] = table.getColumnName(i);
}

ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i);
System.out.println(columnName[i-1]);
}

Try this.
ResultSetMetaData meta = resultset.getMetaData();
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = new String[columncount];
while(count<=columncount){
columnNames [count-1] = meta.getColumnLabel(count);
count++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.

Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);

Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc

rs.getMetaData().getColumnName(int i);
and do not concat the query param!

Related

How to get column name list from java.sql.ResultSet [duplicate]

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 5 years ago.
try{
connection = dataSource.getConnection();
callableStatement.setInt(2, clientId);
....... // some stuff
resultSet = callableStatement.executeQuery();
}
Now I have a resultSet , but don't know column names? How do I retrive that?
try this...
ResultSetMetaData rsmd = resultSet.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
}
resultSet.getMetadata() returns you a ResultSetMetaData object that has the column names (e.g. resultSet.getMetadata().getColumnName(1) )
show this:
ResultSetMetaData rsmd = resultSet.getMetaData();
String name = rsmd.getColumnName(1);
you can use ResultSetMetaData
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
Following code helps to get the column names of the table.
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsCount = rsmd.getColumnCount();
int i=1;
while (i <= columnsCount){
String columnName = rsmd.getColumnName(i);
i++;
}

Sqite select query row doesn't work

I use JDBC to get data from sqlite data base. In DB I have 3 column - login, password and role. I try find row by login, but it doesn't work , and I have exeption when I try getString("password") or "role", where is the mistake? Thanks
resSet = statmt.executeQuery("SELECT * FROM users WHERE login='"+login+"';");
if( hasUser( login)){
System.out.println("User finded:");
while(resSet.next()) {
System.out.println("login = " + resSet.getString("login"));
// !exeption
System.out.println("password = " + resSet.getString("password"));
// !exeption
System.out.println("role = " + resSet.getString("role"));
System.out.println();
}
}else{
System.out.println( "User not found");
}
You can check to see what column names are being returned.
ResultSetMetaData rsmd = resSet.getMetaData();
int colCount = rsmd.getColumnCount();
String rValue = "";
for (int i = 1; i <= colCount ; i++){
String name = rsmd.getColumnName(i);
rValue += name + " ";
}
System.out.println(rValue);
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
metaData.getColumnLabel(i));
}
Refer to this ans..ans see what are the names of your columns in resultant set
http://stackoverflow.com/questions/19094999/java-how-to-get-column-name-on-result-set

how to correctly MySQL "desc table" via java connectivity

I am actually building a project where the names of tables present in databases of mysql are displayed in a list in java.
user selects a table from a list and the description of that table in given using "desc tablename" command.
The problem is, it is supposed to get every field in table but it only gets first field. Below i have explained it more, but first heres my code-:
try {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
String z = jList2.getSelectedValue().toString();
try {
Class.forName("java.sql.DriverManager");
} catch (ClassNotFoundException e) {
timeget();
jTextArea4.append(now + ": " + "/ Failed in getting Driver \n Error Message: " + e.getMessage() + " / \n \n");
JOptionPane.showMessageDialog(this, e.getMessage());
}
DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/", "" + k, "" + j);
stmnt = (Statement) con.createStatement();
String query = "desc " + z;
jTextArea5.append(now + ": " + "/ desc " + z + "; / \n \n");
ResultSet rs = stmnt.executeQuery(query);
String[] cnames = {"Field", "Type", "Null", "Key", "Extra"};
tableModel.setColumnIdentifiers(cnames);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
catch(SQLException e){//some blabla}
Now for detailing into problem->
Say from the list, i select a table called "city". Originally, it has four fields- ID, Name, Population, CountryCode. But in my jTable, only "ID" appears.
the code...
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
...is simply to remove fields of old table when a new table is selected from list.
Hope i clarified my prob.
Please help regarding this. Thanks.
the problem is in this
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
you are not continuing the loop
change the if loop to while loop
while(rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}

Getting columnnames and then replace it into rs.getString()?

I am connecting to a sqlite database and grabbing all the columnnames. What i need help with is by putting those columnnames in rs.getString and inserting the values which are grabbed in a String Array which then can be set on the tablemodel.
My code now:
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
String name = rsmd.getColumnName(i);
System.out.println(name);
// Do stuff with name
model.setColumnCount(i);
}
while ( rs.next() ) {
String value1 = "";
String value2 = "";
String value3 = "";
String value4 = "";
value1 = rs.getString("SNO");
value2 = rs.getString("SNAME");
value3 = rs.getString("STATUS");
value4 = rs.getString("CITY");
model.addRow(new Object[] { value1,value2,value3,value4});
}
What i would want it to be:
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
String name = rsmd.getColumnName(i);
System.out.println(name);
// Do stuff with name
model.setColumnCount(i);
}
while ( rs.next() ) {
String values[];
values[] = rs.getString(name);
model.addRow(new Object[] {values[]});
}
Don't keep calling model.setColumnCount(i);. Just set it once (outside the for loop), like this model.setColumnCount(columnCount); Also
// Do stuff with name
model.setColumnCount(i); // Not this...
// Do stuff with name
model.setColumnName(i, name); // Something like this... that is set the name

Retrieving contents of a user-specified table

The code below displays the tuples of an specific table. How can I turn this into dynamic code? So the user would enter the name of the table, then the rows and column names in addition to the content of the table are displayed.
* Keep in mind that res.getInt and res.getString need to be specified as they are. In a dynamic model, I wouldn't need to know the number, type, and name of the columns. *
public void displayTableA()
{
//Connection already established
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM A");
System.out.println("A_code: " + "\t" + "A_name: ");
while (res.next()) {
int r = res.getInt("A_code");
String s = res.getString("A_name");
System.out.println(r + "\t\t" + s);
}
conn.close();
}
Direct answer: The query is just a string. You can build it up from user inputs. Like read the name of the table into a variable, say "String tablename", then
String query="select * from " + tablename;
Then you run the query to get the result set:
ResultSet rs=st.executeQuery(query);
Then get the meta data for the result set:
ResultSetMetaData meta=rs.getMetaData();
Then loop through the columns getting their names:
for (int x=1;x<=meta.getColumnCount();++x)
{
String columnName=meta.getColumnName(x);
... do whatever you want with this column name ...
}
(Note the columns are numbered starting from 1, not 0.)
As to the data itself, if you're just dumping it out, you don't need to know the type. Just do getString on everything. Every data type can be converted to a string. Well, if you have blobs or images you might want to check for those. There's a ResultSetMetaData function to get the column type, I think it's getType or something like that. Check the javadocs.
That said, why do you want to do this? If you're building some sort of tool to be used by developers to do ad hoc queries, okay fine. But I would be extremely cautious about exposing something like this to end users. (a) They would be unlikely to understand the data, and (b) You'd be creating a huge security hole, users could see ANY data in the system. You could potentially wrap this in checks to limit the users to what they're authorized to see, but it's a lot of work to get that right. It's a lot easier to say "here's what you are allowed to see" then to try to say "here's what you're not allowed to see".
public void displayTable(String table)
{
//Connection already established
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM " + table);
ResultSetMetaData rsmd = res.getMetaData();
while (res.next()) {
for(int ii = 1; ii <= rsmd.getColumnCount(); ii++) {
// get type
int type = rsmt.getColumnType(ii);
String value = null;
switch (type) {
case Types.VARCHAR: value = res.getString(ii); break;
}
// print value.
System.out.print(rsmd.getColumnName(ii) + ": " + value);
}
}
conn.close();
}
If you want print a ResultSet in a dynamic query converting a instance of ResultSet in String:
public static String toString(ResultSet rs) throws SQLException {
StringBuilder sb = new StringBuilder();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
Map<Integer, Integer> sizeMap = new HashMap<>();
for (int column = 1; column <= columnCount; column++) {
int size = Math.max(metaData.getColumnDisplaySize(column), metaData.getColumnName(column).length());
sizeMap.put(column, size);
sb.append(StringUtils.rightPad(metaData.getColumnName(column), size));
sb.append(' ');
sb.append(' ');
}
sb.append('\n');
for (int column = 1; column <= columnCount; column++) {
sb.append(StringUtils.rightPad("", sizeMap.get(column), '-'));
sb.append(' ');
sb.append(' ');
}
while(rs.next()) {
sb.append('\n');
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
String str = rs.getString(columnIndex);
if (str == null) {
str = "(null)";
}
sb.append(StringUtils.rightPad(str, sizeMap.get(columnIndex)));
sb.append(' ');
sb.append(' ');
}
}
return sb.toString();
}
For print something like that:
user_id user_code date_update
------------ -------------------- -------------------
01006393 00989573 2011-09-29 19:23:46
00984742 20192498 2011-12-21 00:00:00
This method use Commons Lang 3
Note: You should use this with care for avoid memory errors. You can change the sb.append with System.out.print or System.out.println

Categories