I am trying to get certain row records from a db_table into an array list. though this has been done many times, mine is a bit more different.
suppose I have a table in my database like this below:
+---------+--------+--------+
| NAME | BILL | CONTACT|
+---------+--------+--------+
| james | 400 | 024669 |
| Mavis | 700 | 025550 |
| john | 650 | 029510 |
| bendo | 340 | 023579 |
+---------+--------+--------+
and I want an array to display records like this:
[james,400,024669]
[Mavis,700, 025550]
[John,650, 029510]
[bendoo,340,023579]
please how do I achieve that. the code I wrote gave me only a last array. and its:
ArrayList<String> inner = null;
try{
String sql="select Name,Score,Contact from members";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
}
System.out.println(inner);
}catch(Exception e){
}
but this is the only System.out.PrintIn displayed:
[bendoo,340,023579]
BUILD SUCCESSFUL (total time: 2 minutes 13 seconds)
please how do I get this below as my result:
[james,400,024669]
[Mavis,700, 025550]
[John,650, 029510]
[bendoo,340,023579]
You need to add inner to a global list. Otherwise you lose the row value every time, and keep only the last one.
Your code should be changed to something like:
ArrayList<String> inner = null;
try {
String sql = "select Name, Score, Contact from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
List<List<String>> allRows = new ArrayList<List<String>>(); // add this!
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
System.out.println("ROW: "+row); // Add this line.
allRows.add(inner); // add this line!
}
for (List<String> row : allRows) {
System.out.println(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
please this is what I have fully so far..
ArrayList<String> inner = null;
try {
String sql = "select Name,Score, Contact from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
List<List<String>> allRows = new ArrayList<List<String>>(); // add this!
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
allRows.add(inner); // add this line!
}
for (List<String> row : allRows) {
System.out.println(row);
}
} catch (SQLException e) {
}
try{
// initialise SMS object.
ZenophSMS sms = new ZenophSMS();
sms.setUser("example#gmail.com");
sms.setPassword("xxxxxxx");
sms.authenticate();
// set message parameters.
sms.setMessage("Hello {$name}, your score is {$score} . please come for you money ");
sms.setSenderId("NICE ONE");
sms.setMessageType(MSGTYPE.TEXT);
// add destinations.
for ( ArrayList<String> recpt : allRows) sms.addRecipient(recpt.get(2), new String[] {recpt.get(0), recpt.get(1)}, false);
// submit the message. Since the total number of destinations is
// less than 400, the submit status of the destinations will be returned.
List<String[]> resp = sms.submit();
// show the status
for (String[] dest : resp)
{ REQSTATUS st = REQSTATUS.fromInt(Integer.parseInt(dest[0]));
if (null != st)
switch (st) {
case SUCCESS:
System.out.println("Submitted: %s"+ dest[1]);
break;
case ERR_INSUFF_CREDIT:
System.out.println("Insufficient Credits: %s"+dest[1]);
break;
default:
System.out.println("Failed: %s"+ dest[1]);
break;
}
}
}
catch (SMSException ex) { System.out.println("Error: " + ex.getMessage()); }
catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); }
this line cant find the array 'allRows'. please what do I do.its giving me an error message that variable cannot be found.
for ( ArrayList<String> recpt : allRows) sms.addRecipient(recpt.get(2),new String[] {recpt.get(0), recpt.get(1)}, false);
Move "inner = new ArrayList<>();" before the "while" statement. You are reinitializing the arraylist for every row.
Related
I am performing a POC to check Streaming API stability, POC is as follows
Program 1 : subscribe to pushtopic created against Account object
Program 2 : create, update & delete single record after every 10 min interval
Both this programs were kept running for more than 12 hours (left overnight), after that I verified if all notification are received or not and found that after sometime (in this case it was nearly ~ 2 hours 45 min ) no notification were received, I repeated this twice and both case it stops getting notification after sometime.
Test code used
Streaming API client (using EMP connector)
public class SFPoc {
static Long count = 0L;
static Long Leadcount = 0L;
public static void main(String[] argv) throws Exception {
String userName = "<user_name>";
String password = "<pwd>";
String pushTopicName = "/topic/AccountPT";
String pushTopicNameLead = "/topic/Leadwhere";
long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;
String securityToken = "<token>";
BayeuxParameters custom = getBayeuxParamWithSpecifiedAPIVersion("37.0");
BayeuxParameters params = null;
try {
params = login(userName, password + securityToken, custom);
} catch (Exception e) {
e.printStackTrace();
}
Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++count));
Consumer<Map<String, Object>> consumerLead = event -> System.out.println(String.format("****** LEADS ***** Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++Leadcount));
EmpConnector connector = new EmpConnector(params);
connector.start().get(10, TimeUnit.SECONDS);
TopicSubscription subscription = connector.subscribe(pushTopicName, replayFrom, consumer).get(10, TimeUnit.SECONDS);
TopicSubscription subscriptionLead = connector.subscribe(pushTopicNameLead, replayFrom, consumerLead).get(10, TimeUnit.SECONDS);
System.out.println(String.format("Subscribed: %s", subscription));
System.out.println(String.format("Subscribed: %s", subscriptionLead));
}
private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
BayeuxParameters params = new BayeuxParameters() {
#Override
public String version() {
return apiVersion;
}
#Override
public String bearerToken() {
return null;
}
};
return params;
}
}
Code which is doing record create/update/delete periodically to generate events
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.time.LocalDateTime;
public class SFDCDataAdjustment {
static final String USERNAME = "<username>";
static final String PASSWORD = "<pwd&securitytoken>";
static EnterpriseConnection connection;
static Long count = 0L;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
// run the different examples
while (true) {
createAccounts();
updateAccounts();
deleteAccounts();
Thread.sleep(1 * 10 * 60 * 1000);
}
} catch (ConnectionException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// queries and displays the 5 newest contacts
private static void queryContacts() {
System.out.println("Querying for the 5 newest Contacts...");
try {
// query for the 5 newest contacts
QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name " +
"FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Contact
Contact c = (Contact)queryResults.getRecords()[i];
System.out.println("Id: " + c.getId() + " - Name: "+c.getFirstName()+" "+
c.getLastName()+" - Account: "+c.getAccount().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// create 5 test Accounts
private static void createAccounts() {
System.out.println("Creating a new test Account...");
Account[] records = new Account[1];
try {
// create 5 test accounts
for (int i=0;i<1;i++) {
Account a = new Account();
a.setName("OptyAccount "+i);
records[i] = a;
}
// create the records in Salesforce.com
SaveResult[] saveResults = connection.create(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR creating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// updates the 5 newly created Accounts
private static void updateAccounts() {
System.out.println("Update a new test Accounts...");
Account[] records = new Account[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
// modify the name of the Account
a.setName(a.getName()+" -- UPDATED");
records[i] = a;
}
}
// update the records in Salesforce.com
SaveResult[] saveResults = connection.update(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR updating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// delete the 5 newly created Account
private static void deleteAccounts() {
System.out.println("Deleting new test Accounts...");
String[] ids = new String[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
// add the Account Id to the array to be deleted
ids[i] = a.getId();
System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
}
}
// delete the records in Salesforce.com by passing an array of Ids
DeleteResult[] deleteResults = connection.delete(ids);
// check the results for any errors
for (int i=0; i< deleteResults.length; i++) {
if (deleteResults[i].isSuccess()) {
System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = deleteResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR deleting record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Further updates got below mentioned error after which notification were
2017-03-09T19:30:28.346 ERROR [com.salesforce.emp.connector.EmpConnector] - connection failure, reconnecting
org.cometd.common.TransportException: {httpCode=503}
at org.cometd.client.transport.LongPollingTransport$2.onComplete(LongPollingTransport.java:278)
at org.eclipse.jetty.client.ResponseNotifier.notifyComplete(ResponseNotifier.java:193)
After this reconnect also happened and handshake also happened but error seems to be in resubscribe() EMP connector seems to be not able to resubscribe for some reason
Note I am using "resubscribe-on-disconnect" branch of EMP connetor
We have determined there was a bug on the server side in a 403 case. The Streaming API uses a session routing cookie and this cookie periodically expires. When it expires, the session is routed to another server, and this responds with a 403. In the current version, this 403 response does not include connect advice, and the client does not attempt to reconnect. This has been fixed and the fix is currently live. My understanding is that this should fix the reconnect problem exhibited by the clients.
I've found one totally working query, which gets columns and their data from Oracle DB and puts the output in console printout.
I've spent 3 hours trying to display this data in Swing JTable.
When I am trying to bind data with JTable:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
data, header
));
it keeps telling me that constructor is invalid. That's true, because I need arrays [] and [][] to make that. Any ideas how this can be implemented?
Here is the original query:
package com.javacoderanch.example.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class MetadataColumnExample {
private static final String DRIVER = "oracle.jdbc.OracleDriver";
private static final String URL = "jdbc:oracle:thin:#//XXX";
private static final String USERNAME = "XXX";
private static final String PASSWORD = "XXX";
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
//
// As the usual ritual, load the driver class and get connection
// from database.
//
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//
// In the statement below we'll select all records from users table
// and then try to find all the columns it has.
//
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select *\n"
+ "from booking\n"
+ "where TRACKING_NUMBER = 1000001741");
//
// The ResultSetMetaData is where all metadata related information
// for a result set is stored.
//
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
//
// To get the column names we do a loop for a number of column count
// returned above. And please remember a JDBC operation is 1-indexed
// so every index begin from 1 not 0 as in array.
//
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
//
// Later we use the collected column names to get the value of the
// column it self.
//
while (resultSet.next()) {
for (String columnName : columns) {
String value = resultSet.getString(columnName);
System.out.println(columnName + " = " + value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
}
}
}
Ok I found a bit better way adding SQL query to JTable without even using the ArrayList. Maybe will be helpful for someone, completely working:
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.image.BufferedImage;
public class report extends JFrame {
PreparedStatement ps;
Connection con;
ResultSet rs;
Statement st;
JLabel l1;
String bn;
int bid;
Date d1, d2;
int rows = 0;
Object data1[][];
JScrollPane scroller;
JTable table;
public report() {
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
setSize(600, 600);
setLocation(50, 50);
setLayout(new BorderLayout());
setTitle("Library Report");
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#XXXXX", "XXXXX", "XXXXX");
} catch (Exception e) {
}
try {
/*
* JDBC 2.0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all the rows
* So we add TYPE_SCROLL_INSENSITIVE & CONCUR_READ_ONLY
*/
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //Creating Statement Object
} catch (SQLException sqlex) {
System.out.println("!!!###");
}
try {
rs = st.executeQuery("select TRACKING_NUMBER, INCO_TERM_CODE, MODE_OF_TRANSPORT\n"
+ "from salog.booking\n"
+ "where rownum < 5");
// Counting rows
rs.last();
int rows = rs.getRow();
rs.beforeFirst();
System.out.println("cc " + rows);
ResultSetMetaData metaData = rs.getMetaData();
int colummm = metaData.getColumnCount();
System.out.println("colms =" + colummm);
Object[] Colheads = {"BookId", "BookName", "rtyry"};
if (Colheads.length != colummm) {
// System.out.println("EPT!!");
JOptionPane.showMessageDialog(rootPane, "Incorrect Column Headers quantity listed in array! The program will now exit.", "System Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
data1 = new Object[rows][Colheads.length];
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < Colheads.length; j1++) {
data1[i1][j1] = rs.getString(j1 + 1);
}
}
JTable table = new JTable(data1, Colheads);
JScrollPane jsp = new JScrollPane(table);
getContentPane().add(jsp);
} catch (Exception e) {
}
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
JFrame frm = new report();
frm.setSize(600, 600);
frm.setLocation(50, 50);
BufferedImage image = null;
frm.setIconImage(image);
frm.setVisible(true);
frm.show();
}
}
I had the error in this code snippet:
private String[][] connectToDB(String query) throws ClassNotFoundException{
String[][] results = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:/EACA_AgroVentures1.accdb";
conn = DriverManager.getConnection(db);
stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsm = rs.getMetaData();
rs.beforeFirst();
int columns = rsm.getColumnCount();
int rows = getRowCount(rs);
//int rows = rs.getFetchSize();
int rowCount = 0;
results = new String[rows][columns];
//System.out.println(rows+" "+columns);
while((rs!=null) && (rs.next())){
for(int i = 1; i < columns; i++){
results[rowCount][i-1] = rs.getString(i); // --> ERROR SHOWS HERE
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
rowCount++;
}
rs.getStatement().close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
return results;
}
My query consists of the following:
private void loadMR(){
try {
String query = "SELECT dealerCode, SUM(kg) AS totalKG, SUM(price) AS totalPrice, returnDate, BID FROM meatReturns GROUP BY BID, dealerCode, returnDate;";
Object[][] result = connectToDB(query);
// some more code below..
I tried using the first code with some other query given in another method:
private void loadDealers(){
try {
String query = "SELECT * FROM Dealers";
Object[][] result = connectToDBWithRows(
query);
// some more code..
and it runs perfectly well. What is going on here? How can i fix this problem?
UPDATE: the only difference of connectToDBWithRows and connectToDB is the while loop that manages the resultSet
// Snippet from connectToDBWithRows()
while((rs!=null) && (rs.next())){
for(int i = 0; i < columns; i++){
if (i == 0){
// Do nothing
}else{
results[rowCount][i] = rs.getString(i);
//System.out.println(rowCount+","+i+" = "+rs.getString(i));
}
}
rowCount++;
}
and this is my getRowCount() method
private int getRowCount(ResultSet resultSet){
int size = 0;
try {
resultSet.last();
size = resultSet.getRow();
resultSet.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return size;
}
I've noticed that sometimes, Access needs you to specify the table name when referring to columns in sql statements. Try the following:
private void loadMR(){
try {
String query = "SELECT meatReturns.dealerCode, SUM(meatReturns.kg) AS totalKG, SUM(meatReturns.price) AS totalPrice, meatReturns.returnDate, meatReturns.BID FROM meatReturns GROUP BY meatReturns.BID, meatReturns.dealerCode, meatReturns.returnDate";
Object[][] result = connectToDBWithRows(query);
I try to code a forum using java swing. Firstly, on click for the jTable, it will lead to eForumContent.class which pass in the id together.
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int id = 0;
eForumTopics topics = new eForumTopics(id);
topics.retrieveDiscussion();
eForumThreadContent myWindow = new eForumThreadContent(id);
myWindow.getJFrame().setVisible(true);
}
});
I initialize the id first. But I set my id in database table to auto number. Then I call the retrieveDiscussion method to get the id from database and pass it to eForumThreadContent. Here are my codes for retrieveDiscussion method.
public boolean retrieveDiscussion(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String dbQuery = "SELECT * FROM forumTopics WHERE topic_id = '" + id
+ "'";
rs = db.readRequest(dbQuery);
db.terminate();
return success;
}
}
Then, inside the eForumThreadContent, I want to display the content of chosen thread using a table. So I use the id which I pass in just now and insert into my sql statement. Here are my codes.
public eForumThreadContent(int id) {
this.id = id;
}
if (jTable == null) {
Vector columnNames = new Vector(); // Vector class allows dynamic
// array of objects
Vector data = new Vector();
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = '"+id+"'";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(400); // second column is bigger
}else {
column.setPreferredWidth(200);
}
}
String header[] = { "Title", "Description", "Posted by" };
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel()
.getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.getTableHeader().setFont( new Font( "Dialog" , Font.PLAIN, 20 ));
jTable.getTableHeader().setForeground(Color.white);
jTable.getTableHeader().setBackground(new Color(102, 102, 102));
jTable.setEnabled(false);
jTable.setRowHeight(100);
jTable.getRowHeight();
jTable.setFont( new Font( "Dialog" , Font.PLAIN, 18 ));
}
return jTable;
}
However, the table inside eForumThreadContent is empty even when I clicked on certain thread. It also gives me an error message.
[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at DBController.database.DBController.readRequest(DBController.java:27)
at kioskeForum.entity.eForumTopics.retrieveDiscussion(eForumTopics.java:67)
at kioskeForum.ui.eForumDiscussion$3.mouseClicked(eForumDiscussion.java:296)
I research online to get an idea for topic views using id. But my table does not show up anything. Can somebody enlighten me how to fix it? Or any other ways to display topic views in java swing? Thanks in advance.
I know this may be stupid question i am gonna put here since i am a complete java noob. may be you guys can help me out to get this problem solved.
I am working on an application where a user would need the result dislayed on jsp page in pdf form, and the pdf is being generated as output stream in HTTP request, means when a user clicks on a button(on jsp) to generate PDF with result i.e. PDF getting generated on fly and sent to client browser.
Using iText, i am able to generate custom generated pdfs on the fly
Heres the Code snippet
public class PdfSample extends HttpServlet {
public PdfSample() {
super();
}
//connection to DB.... code goes here.....
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws javax.servlet.ServletException, java.io.IOException {
DocumentException ex = null;
ByteArrayOutputStream baosPDF = null;
try {
baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("filename_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
resp.setHeader("Cache-Control", "max-age=30");
resp.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
resp.setHeader("Content-disposition", sbContentDispValue.toString());
resp.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = resp.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
} catch (DocumentException dex) {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println(this.getClass().getName() + " caught an exception: "
+ dex.getClass().getName() + "<br>");
writer.println("<pre>");
dex.printStackTrace(writer);
writer.println("</pre>");
} finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
}
protected ByteArrayOutputStream generatePDFDocumentBytes(
final HttpServletRequest req, final ServletContext ctx)
throws DocumentException
{
Document doc = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null;
try {
docWriter = PdfWriter.getInstance(doc, baosPDF);
doc.addAuthor("Sample");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("Sample");
doc.addTitle("Sample Report");
doc.setPageSize(PageSize.LETTER);
doc.open();
String strServerInfo = ctx.getServerInfo();
if (strServerInfo != null) {
}
doc.add(makeHTTPParameterInfoElement(req));
} catch (DocumentException dex) {
baosPDF.reset();
throw dex;
} finally {
if (doc != null) {
doc.close();
}
if (docWriter != null) {
docWriter.close();
}
}
if (baosPDF.size() < 1) {
throw new DocumentException("document has " + baosPDF.size()
+ " bytes");
}
return baosPDF;
}
protected Element makeHTTPParameterInfoElement(final HttpServletRequest req) {
Table tab = null;
tab = makeTable("", "White Color Car", "Black Color Car", "Total");
return (Element) tab;
}
private static Table makeTable(final String firstColumnTitle,
final String secondColumnTitle, final String thirdColumnTitle,
final String fourthColumnTitle) {
Paragraph paragraph, paragraph1;
int val1 = 0;
int val2 = 0;
int val3 = 0;
int val4 = 0;
Table tab = null;
try {
tab = new Table(4);
} catch (BadElementException ex) {
throw new RuntimeException(ex);
}
Cell c = null;
try {
paragraph = new Paragraph("Car Report");
paragraph.setAlignment(1);
c = new Cell(paragraph);
c.setColspan(tab.getColumns());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tab.setBorderWidth(1);
tab.setBorderColor(Color.BLACK);
tab.setPadding(2);
tab.setSpacing(3);
tab.setBackgroundColor(Color.WHITE);
tab.addCell(c);
tab.addCell(new Cell(firstColumnTitle));
tab.addCell(new Cell(secondColumnTitle));
tab.addCell(new Cell(thirdColumnTitle));
tab.addCell(new Cell(fourthColumnTitle));
tab.endHeaders();
String startDate1 = "01/06/2011";
String endDate1 = "11/09/2011";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date startDate = sdf1.parse(startDate1);
Date endDate = sdf1.parse(endDate1);
java.sql.Date sdate = new java.sql.Date(startDate.getTime());
java.sql.Date edate = new java.sql.Date(endDate.getTime());
String newWhiteColor = "select count(*) from .......";
String newBlackColor = "select count(*) from .......";
String totalWhiteColor= "select count(*) from .....";
String totalBlackColor = "select count(*) from .......";
Connection connection = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
PreparedStatement preparedStatement3 = null;
ResultSet resultSet = null;
ResultSet resultSet1 = null;
ResultSet resultSet2 = null;
ResultSet resultSet3 = null;
connection = getSimpleConnection1();
// New Car recently sold out - White Color
preparedStatement = connection
.prepareStatement(newWhiteColor);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
val1 = resultSet.getInt(1);
}
// New Car recently sold out - Black Color
preparedStatement3 = connection
.prepareStatement(newBlackColor);
resultSet3 = preparedStatement3.executeQuery();
while (resultSet3.next()) {
val2 = resultSet3.getInt(1);
}
// Total White Color cars sold out
preparedStatement1 = connection
.prepareStatement(totalWhiteColor);
resultSet1 = preparedStatement1.executeQuery();
while (resultSet1.next()) {
val3 = resultSet1.getInt(1);
}
// Total Black Color cars sold out
preparedStatement2 = connection
.prepareStatement(totalBlackColor);
resultSet2 = preparedStatement2.executeQuery();
while (resultSet2.next()) {
val4 = resultSet2.getInt(1);
}
Integer newWhite = val1;
Integer newBlack = val2;
Integer totalWhite = val3;
Integer totalBlack = val4;
Integer totalNewCars = newWhite + new Black;
Integer totalCars= totalWhite + totalBlack ;
tab.addCell(new Cell("New Cars Sold Out"));
tab.addCell(new Cell(newWhite.toString()));
tab.addCell(new Cell(newBlack.toString()));
tab.addCell(new Cell(totalNewCars.toString()));
tab.addCell(new Cell("Total Cars Sold out"));
tab.addCell(new Cell(totalWhite.toString()));
tab.addCell(new Cell(totalBlack.toString()));
tab.addCell(new Cell(totalCars.toString()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tab;
}
}
The Above code fetching the data (count) from the database by making the connection and displaying in cells. with the above code i am able to create pdf on fly and output as showing below.
--------------------------------------------------------------------------------------------------
Car Report
--------------------------------------------------------------------------------------------------
| White Color Car |Black Color Car | Total
--------------------------------------------------------------------------------------------------
New Cars Sold out| 5 | 8 | 13
--------------------------------------------------------------------------------------------------
Total Cars Sold Out| 6 | 4 | 10
--------------------------------------------------------------------------------------------------
Query 1) How Can I align the car report in Center?
Query 2) Data and text are being displayed inside a cell, how can i set the border of the cell to "0".
Query 3) How can i color a particular cell ( the blank one)?
Query 4) Is it possible to Insert a image on top of the header of the pdf?
Any help would be greatly appreciated !!!!!
Query 1) How Can I align the car report in Center?
Solution : c.setHorizontalAlignment(Element.ALIGN_CENTER);