ResultSetMetaData to Filewriter/CSV issue JAVA - java

This code prints 4 data headers and data below in my CSV file correctly in columns A-D
However, in columns E-H there is a Random set of data.
ResultSetMetaData rsmd = result.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount + 1; i++) {
String name = rsmd.getColumnName(i);
out.print(name);
if (i != columnCount + 1) {
out.print(",");
System.out.print(i);
}
}
while (result.next()) {
out.println(String.format("%s,%s,%s,%s", result.getString(1),
result.getString(2), result.getString(3),
result.getString(4)));
}
result.close();
statement.close();

There is no newline character being written after the column names have been written, resulting in the first row of data appearing as column headers. Write a newline character after the for loop that writes the column names.

Related

How to return multiple rows from result set object to send servlet

I have a class it retrieve number of rows from database but here i return result set object to servlet class and based on those rows i need to display in table when i retrieve table it shows single row only but when i execute same query it shows in Database having two rows may be i didn't return result set object properly can anyone help me to retrieve all the all records from database.
Servlet :
WorkAreaClass wa=new WorkAreaClass();
ResultSet resultSet = wa.workarea(User);
if(resultSet.next())
{
table(resultSet,out);
}
You're calling if(resultSet.next()) before you start to iterate the resultset. After that you'll be on the first row. Then when you enter your while(rs.next()) loop, the cursor is moved to the second row.
You can convert the while loop into a do-while and it won't skip the first row.
Suppose #kayaman solution is correct.
Simply your table should be like this.
public int table( ResultSet rs, PrintWriter out)throws Exception
{
int rowcount=0;
out.println("<P ALIGN='center'><TABLE BORDER=1>");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// table header
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TH>" + rsmd.getColumnLabel(i + 1) + "</TH>");
}
out.println("</TR>");
// the data
do {
rowcount++;
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TD>" + rs.getString(i + 1) + "</TD>");
}
out.println("</TR>");
} while(rs.next());
out.println("</TABLE></P>");
return rowcount;
}
You need to use JDBCRowSet https://docs.oracle.com/javase/tutorial/jdbc/basics/jdbcrowset.html
here is short demo:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select * from COFFEES");
JdbcRowSetImpl jdbcRs = new JdbcRowSetImpl(rs);

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

Exporting Database Query to CSV file, PostgreSQL & Java

As the title states, I'm exporting a java query from a local database into a CSV file, all the required information prints out correctly, however my column headers Print out in Column A (row 1-8) and not along columns (A-H). in short i have headers 1-8 printing in column 1, followed by thousands of rows of data in the correct order. Pretty new to java, sorry if I'm being silly!
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("TestingRawData.csv")));
ResultSetMetaData rsmd = result.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount + 1; i++) {
String name = rsmd.getColumnName(i);
out.println(name);
// print the name
}
while (result.next()) {
out.println(String.format("%s,%s,%s,%s,%s,%s,%s,%s",
result.getString(1), result.getString(2),
result.getString(3), result.getString(4),
result.getString(5), result.getString(6),
result.getString(7), result.getString(8)));
}
Apart from the fact that this should be done using a CSV library such as OpenCSV,
println outputs a newline. Use print instead
for (int i = 1; i < columnCount + 1; i++) {
String name = rsmd.getColumnName(i);
out.print(name);
if (i != columnCount + 1) {
out.print(",");
}
}

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

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!

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