I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
Related
See Below. rs.getString("tags") is subquery with more than 1 row. I want to iterate that subquery(rs.getString("tags") ---- Like rs.next().
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("id"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
while(rs.getString("tags").next()){
arrtags[i] = rs.getString(1);
}
emaildto.setTags(arrtags);
rs.getString("tags") does not work --- and contain more than 1 rows. How to extract it. Is there any technique?
Try something like this:
Array tagsArray = rs.getArray("tags");
String[] tags = (String[])tagsArray.getArray();
this is not answer. this is complete code
List emails = new ArrayList();
String listQuery = "select mid, sub, message, "
+ " (select emailid from sub_ids where sub_ids.messageid= sub_mail_list.mid ) // this query fetch more than one row.
as refid"
+ " from sub_mail_list";
PreparedStatement ps = null;
ResultSet rs;
try {
ps = DatabaseConnectionUtil.getConnection().prepareStatement(
listQuery);
rs = ps.executeQuery(listQuery);
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("mid"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
Array tagsArray = rs.getArray("refid");
List<vtbDto> vtbdtosvr = new ArrayList<vtbDto>();
int[] tags = (int[])tagsArray.getArray();
for (int i = 0; i < tags.length; i++) {
vtbDto vtbdto = new vtbDto();
vtbdto.setRefid(tags[i]);
vtbdtosvr.add(vtbdto);
}
emaildto.setAr(tagsArray);
emails.add(emaildto);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DatabaseConnectionUtil.closeAll(ps);
}
return emails;
And this is code to print function
List emailDtos = emaildao.getAllemails();
for (emailDto emailDto2 : emailDtos) {
System.out.println( emailDto2.getMid());
System.out.println( emailDto2.getSub());
System.out.println( emailDto2.getMessage());
List<vtbDto> vtbdtos= emailDto2.getVtbdtolst();
for (vtbDto vtbdto2 : vtbdtos) {
System.out.print(vtbdto2.getRefid() + ", ");
}
}
and the console print "Subquery returns more than 1 row";
I use a jTable jquery for jsp page, it work very well. It can display the showing count records in bottom right of table well (e.g. Showing 1-10 of 22). When I insert the Filtering into the page, the showing count record is not correctly.
I follow this for Filtering: http://www.jtable.org/Demo/Filtering
How to customize the code for showing count record (I use java-jsp and sql server). Sorry for my English language :))
Here is the code I am using right now in controller.
if (action.equals("list")) {
try {
int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
int numRecordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
String jtSorting = null;
//Fetch Data from Rejected_Product Table
lstSite = dao.**getAllSite**(filter_site, startPageIndex, numRecordsPerPage, jtSorting);
//Get Total Record Count for Pagination
int siteCount = dao.**getSiteCount**();
//Convert Java Object to Json
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(lstSite, new TypeToken<List<Site>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
//Return Json in the format required by jTable plugin
listData = "{\"Result\":\"OK\",\"Records\":"+listData+",\"TotalRecordCount\":"+siteCount+"}";
response.getWriter().print(listData);
System.out.println(listData);
} catch (Exception ex) {
String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getStackTrace() + "}";
response.getWriter().print(error);
ex.printStackTrace();
}
}
and here method getAllSite:
public List<Site> getAllSite (FilterSite filter_site, int jtStartIndex, int jtPageSize, String jtSorting) {
List<Site> siteList = new ArrayList<Site>();
String query = "";
String siteQ = filter_site.getSite();
String clientQ = filter_site.getClient(); // wait
String locationQ = filter_site.getLocation();
if (locationQ.isEmpty()) {
locationQ = "";
} else {
locationQ = "and location like '%"+locationQ+"' ";
}
String site_idQ = filter_site.getSite_id();
if (site_idQ.isEmpty()) {
site_idQ = "";
} else {
site_idQ = "and site_id = '"+site_idQ+"' ";
}
String divisionQ = filter_site.getDivision();
if (divisionQ.isEmpty()) {
divisionQ = "";
} else {
divisionQ = "and division = '"+divisionQ+"' ";
}
int range = jtStartIndex+jtPageSize;
query = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY CODE) as row FROM [site]) a "
+ "WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+") "
+ "and row > "+jtStartIndex+" and row <= "+range;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
System.out.println("query : "+query);
while (rs.next()) {
Site sitebean = new Site();
sitebean.setName(rs.getString("name"));
sitebean.setCode(rs.getString("code"));
.....
siteList.add(sitebean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return siteList;
}
and here method getSiteCount :
public int getSiteCount () {
int count = 0;
String query = "SELECT COUNT(*) as count FROM [site] ";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
count = rs.getInt("count");
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
If you mean by "not correctly" that the row count is larger than expected, then the solution would be to include the where clause in the siteCount query.
WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+")
I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
public void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows = new Vector();
for (int i=1; i<columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
for (int j=1; j<columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblPatient.setModel(dtm);
}
On my ResultSet rs = state.executeQuery() I used this SQL
"SELECT "
+ "pIDNo AS 'Patient ID',"
+ "pLName AS 'Last Name',"
+ "pFName AS 'First Name',"
+ "pMI AS 'M.I.',"
+ "pSex AS 'Sex',"
+ "pStatus AS 'Status',"
+ "pTelNo AS 'Contact No.',"
+ "pDocID AS 'Doctor ID',"
+ "pAddr AS 'St. No.',"
+ "pStreet AS 'St. Name',"
+ "pBarangay AS 'Barangay',"
+ "pCity AS 'City',"
+ " pProvince AS 'Province',"
+ " pLNameKIN AS 'Last Name',"
+ "pFNameKIN AS 'First Name',"
+ "pMIKIN AS 'M.I.',"
+ "pRelationKIN AS 'Relation',"
+ "pTotalDue AS 'Total Due'"
+ " FROM dbo.Patients");
First I run this line (pTotalDue didn't come up to jTable.)
And on my second attempt to display it I do this:
"SELECT pTotalDue AS 'Total Due' FROM dbo.Patients"
Now I tried this one, and I think something's really wrong about my codes. BTW this column has MONEY DATA TYPE
why does it didn't show to my JTable? could anyone tell me what is the problem with my codes?
(Problem in the answer that has given to me)
public class QueryOnWorkerThread extends SwingWorker{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:OJT_dsn";
String user = "sa";
String pass = "";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
`#Override <<<<<<<<<<<<<<<<<<<<< I have a problem here it says : done() in javaapplication25.SearchPatient.QueryWorkerThread cannot override done() in javax.swing.SwingWorker overriden method does not throw java.lang.Exception , what does it mean sir?`
protected void done() throws Exception{
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
try this
DefaultTableModel dtm=(DefaultTableModel)table.getModel();
for (int i = dtm.getRowCount() - 1; i > -1; i--) {
dtm.removeRow(i);
}
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("Your SQL Query");
while(rs.next())
{
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=rs.getString(3);
String str4=rs.getString(4);
String str5=rs.getString(5);
:
:
:
dtm.addRow(new Object[]{str1,str2,str3,str4,str5});
}
In you loops, your exit condition is
j<columns
this means thant the last column will never be recovered. try this insted:
for (int j=1; j<=columns; j++)
The fact that your last column does not appear is probably related to your loop statements, as already indicated by #Joan.
There are however more issues with this code. You should only update Swing components on the Event Dispatch Thread, and on that Thread you should not perform long running operations. In short, mixing SQL queries and updates of the JTable should not happen on the same thread. Consult the Concurrency in Swing guide for more info.
Using a SwingWorker could solve this issue:
public class QueryOnWorkerThread extends SwingWorker<TableModel, Void>{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
#Override
protected void done() {
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
}
The SwingWorker can be started by calling
QueryOnWorkerThread worker = new QueryOnWorkerThread( tblPatient );
worker.execute();
Note how I changed the loops in your code
Try getting that column via ResultSet.getBigDecimal() rather than via ResultSet.getString(). Then put your retrieved BigDecimal.toPlainString() into your table cell.
Example:
data_rows.addElement(rs.getBigDecimal("pTotalDue").toPlainString());//Assuming your select returns a pTotalDue Column (e.g. SELECT pTotalDue,... FROM ...)
Try to Use an TableCellRenderer.
Implement the Renderer and render the Column with the Money Type in the form you wish.
Regards,
HL
I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}