Populating jtree from oracle db - java

package com.view.custom;
import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.ResultSetMetaData;
import com.util.DBConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class ReadData {
public static String getTableData(Connection con) {
String col_attr1 = "";
try {
ArrayList tablename = new ArrayList();
Statement stt = con.createStatement();
String database = "Source Tables";
ResultSet rs = null;
DatabaseMetaData meta = (DatabaseMetaData) con.getMetaData();
rs = meta.getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) {
String ab = rs.getString("TABLE_NAME");
System.out.println(ab);
tablename.add(ab);
}
for (Object tablename1 : tablename) {
String sql = "Select * from " + tablename1.toString();
String table_name = tablename1.toString();
System.out.println("Table name " + table_name);
ResultSet rs1 = stt.executeQuery(sql);
ResultSetMetaData metadata = (ResultSetMetaData) rs1.getMetaData();
int cou = metadata.getColumnCount();
String col_attr = "";
String profile1 = "";
for (int j = 1; j <= cou; j++) {
String ab = metadata.getColumnName(j);
for (int c = j; c <= cou; c++) {
String val = "";
while (rs1.next()) {
val += rs1.getString(c) + "$";
}
rs1.beforeFirst();
if (val.length() > 1)
val = val.substring(0, val.lastIndexOf("$"));
profile1 += ab + "#" + val + "|";
break;
}
}
profile1 = profile1.substring(0, profile1.lastIndexOf("|"));
col_attr1 += table_name + "#" + profile1 + "\n";
}
} catch (Exception e) {
e.printStackTrace();
}
return col_attr1;
}
public static JTree getTree(String str, String rootName) {
str = str.substring(0, str.lastIndexOf("\n"));
String args[] = str.split("\n");
DefaultMutableTreeNode dt = new DefaultMutableTreeNode(rootName);
for (String arg : args) {
String[] aa = arg.split("#"); // table name
String bb[] = aa[1].split("\\|");
System.out.println("table lenght: " + aa.length);
DefaultMutableTreeNode dm = new DefaultMutableTreeNode(aa[0]);
System.out.println("table : " + aa[0]);
dt.add(dm);
for (String bb1 : bb) {
String[] dd = bb1.split("#"); // col value
DefaultMutableTreeNode dm1 = new DefaultMutableTreeNode(dd[0]);
dm.add(dm1);
if (dd.length > 1) {
String dd1[] = dd[1].split("\\$");
for (String dd11 : dd1) {
DefaultMutableTreeNode dm2 = new DefaultMutableTreeNode(
dd11);
dm1.add(dm2);
}
}
}
}
return new JTree(dt);
}
}
It is not fetching the tree.

Related

ResultSet object reaches the end after one iteration

I'm trying to read all records in a table from a database, and do some processing using those data. Following is the code that I use.
package differences;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class ConformancePercentageChecking {
private final String dbDriver = "com.mysql.jdbc.Driver";
private Connection connection = null;
private final String serverName = "localhost";
private final String mydatabase = "google";
private final String username = "root";//kh hoseinpur
private final String password = "123";
private final String extrainfo = "?useUnicode=true&characterEncoding=UTF-8";
int numberOfInsertedIDs = 0;
public void findConformances() {
try {
try {
Class.forName(dbDriver);//a call to forname("X") causes the class named X to be initialized
String url = "jdbc:mysql://" + serverName + "/" + mydatabase + extrainfo;
if (connection == null) {
connection = (Connection) DriverManager.getConnection(url, username, password);
}
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, "database");
}
String query1, query2, query3, query4, query5, query6, testSuite, id;
PreparedStatement statement1, statement2, statement3, statement4, statement5, statement6;
query1 = "drop table PresConformance;";
query2 = "drop table PostConformance;";
statement1 = connection.prepareStatement(query1);
statement2 = connection.prepareStatement(query2);
statement1.executeUpdate();
statement2.executeUpdate();
query1 = "CREATE TABLE PresConformance(testSuite Text, conformance numeric(10), depthDifference numeric(10),pathLength numeric(10));";
query2 = "CREATE TABLE PostConformance(testSuite Text, conformance numeric(10), depthDifference numeric(10),pathLength numeric(10));";
query3 = "SELECT * FROM presDifference;";
query4 = "SELECT * FROM presdifference;";
query5 = "insert into PresConformance values(?,?,?,?);";
query6 = "insert into PostConformance values(?,?,?,?);";
statement1 = connection.prepareStatement(query1);
statement2 = connection.prepareStatement(query2);
statement3 = connection.prepareStatement(query3);
statement4 = connection.prepareStatement(query4);
statement5 = connection.prepareStatement(query5);
statement6 = connection.prepareStatement(query6);
Map<String, String> map = new HashMap<>();
statement1.executeUpdate();
statement2.executeUpdate();
ResultSet r1, r2, r3, r4;
r1 = statement3.executeQuery();
System.out.println("***1");
r2 = statement4.executeQuery();
System.out.println("***2");
int idCount = 0, depthDifference = 0, totalNumberOfExecutions = 0, testSuitesCounts = 0, difference = 0, pathLength = 0;
float conformancePercentage = 0, sumOfconformancePercentage = 0;
r3 = r1;
r4 = r2;
while (r1.next()) {
testSuitesCounts = 0;
sumOfconformancePercentage = 0;
testSuite = r1.getString("testSuite");
id = null;
id = map.get(testSuite);
if (id == null) {
idCount++;
map.put(Integer.toString(idCount), testSuite);
r3.absolute(r1.getRow());
r3.previous();
while (r3.next()) {
if (testSuite.equals(r3.getString("testSuite"))) {
System.out.println(testSuite + " equal");
totalNumberOfExecutions = r3.getInt("totalNumberOfExecutions");
difference = r3.getInt("difference");
conformancePercentage = (1 - ((float) difference / totalNumberOfExecutions)) * 100;
if (testSuitesCounts == 0) {
String[] testSuite1, testSuite2, testSuite3;
testSuite1 = testSuite.split("_");
testSuite2 = testSuite1[0].split("/");
testSuite3 = testSuite1[1].split("/");
depthDifference = Math.abs(testSuite2.length - 1) - testSuite3.length;
pathLength = (testSuite2.length - 1) + testSuite3.length;
}
testSuitesCounts++;
sumOfconformancePercentage += conformancePercentage;
}
}
statement5.setString(1, testSuite);
statement5.setFloat(2, (sumOfconformancePercentage / testSuitesCounts));
statement5.setInt(3, depthDifference);
statement5.setInt(4, pathLength);
statement5.executeUpdate();
}
System.out.println(r1.getRow());
}
System.out.println("Pres Finished*****************************************");
idCount = 0;
map = new HashMap<>();
while (r2.next()) {
testSuitesCounts = 0;
sumOfconformancePercentage = 0;
testSuite = r2.getString("testSuite");
id = null;
id = map.get(testSuite);
if (id == null) {
idCount++;
map.put(Integer.toString(idCount), testSuite);
r4.absolute(r2.getRow());
r4.previous();
while (r4.next()) {
if (testSuite.equals(r4.getString("testSuite"))) {
System.out.println(testSuite + " equal");
totalNumberOfExecutions = r4.getInt("totalNumberOfExecutions");
difference = r4.getInt("difference");
conformancePercentage = (1 - ((float) difference / totalNumberOfExecutions)) * 100;
if (testSuitesCounts == 0) {
String[] testSuite1, testSuite2, testSuite3;
testSuite1 = testSuite.split("_");
testSuite2 = testSuite1[0].split("/");
testSuite3 = testSuite1[1].split("/");
depthDifference = Math.abs(testSuite2.length - 1) - testSuite3.length;
pathLength = (testSuite2.length - 1) + testSuite3.length;
}
testSuitesCounts++;
sumOfconformancePercentage += conformancePercentage;
}
}
statement6.setString(1, testSuite);
statement6.setFloat(2, (sumOfconformancePercentage / testSuitesCounts));
statement6.setInt(3, depthDifference);
statement6.setInt(4, pathLength);
statement6.executeUpdate();
}
}
System.out.println("Post Finished*****************************************");
System.out.println("Finished Inserting to DB");
} catch (SQLException ex) {
Logger.getLogger(DifferencesPresPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The problem, is that for both ResultSet objects r1 and r3, which contain tables' records, it just iterates once, and then reaches the end of the ResultSet objects.
I tried to count number of records in both ResultSet objects before each while loop, and it correctly prints the number of recoreds, but when it enters in these while loops, it works for only first row of each ResultSet objects.
Can any body help me to find out the result of this problem?
I believe by default your resultsets are TYPE_FORWARD_ONLY. You need to specify TYPE_SCROLL_INSENSITIVE when preparing your prepared statements. Hope this helps.

To import data into mysql

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Formatter;
public class JtoCModified {
private static final String COMMA_DELIMITER = ",";
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION="jdbc:mysql://localhost:3306/test2";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
private static int RECORD_COUNT =24;
static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
static final String DATE_FORMAT = "yyyy-MM-dd";
static final String TIME_FORMAT = "HH:mm:ss";
private static final int ADD_MINUTES = 2;
static final String FromDate = "2016-01-01 00:00:00";
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
List<String> records = new ArrayList<String>();
StringBuffer record = new StringBuffer();
DateFormat d_f = new SimpleDateFormat(DATE_FORMAT);
DateFormat tf = new SimpleDateFormat(TIME_FORMAT);
Calendar cal = Calendar.getInstance();
cal.setTime(d_f.parse(FromDate));
record.append("\t");
for (int i = 1; i <= RECORD_COUNT; i++) {
if (i % 100000 == 0) {
records = new ArrayList<String>(RECORD_COUNT);
}
for (int j = 0; j < 2730; j++) {
int OPV = 230 + j % 15; // 230 - 244 by 1
String String = Integer.toString(OPV);
String str = Integer.toString(OPV);
record.append("OPV");
double IKW = 1.3 + j % 17 * 0.1; // 1.3 - 2.9 by 0.1
String aString = Double.toString(IKW);
String IKW2 = String.valueOf(IKW);
record.append("IKW");
double OKW = 0.01 + j % 49 * 0.01; // 0.01 - 0.49 by 0.01
String bString = Double.toString(IKW);
String OKW2 = String.valueOf(OKW);
record.append("OKW");
double OPI = 0.05 + j % 105 * 0.01; // 0.05 - 1.09 by 0.01
String cString = Double.toString(OPI);
String OPI2 = String.valueOf(OPI);
record.append("OPI");
double IPI = 0.00 + j % 8 * 0.01;
String dString = Double.toString(IPI);
String IPI2 = String.valueOf(IPI);
record.append("IPI");
int NA1 = 000;
String eString = Integer.toString(NA1);
String NA12 = Integer.toString(NA1);
record.append("NA1");
int BVV = 104 + j % 13;
String fString = Integer.toString(BVV);
String BVV2 = Integer.toString(BVV);
record.append("BVV");
double BVI = 1.3 + j % 15 * 0.8;
String gString = Double.toString(BVI);
String BVI2 = String.valueOf(BVI);
record.append("BVI");
int NA2 = 000;
String hString = Integer.toString(NA2);
String NA22 = Integer.toString(NA2);
record.append("NA2");
int NA3 = 000;
String iString = Integer.toString(NA3);
String NA32 = Integer.toString(NA3);
record.append("NA3");
int IPV = 241 + j % 1;
String jString = Integer.toString(IPV);
String IPV2 = Integer.toString(IPV);
record.append("IPV");
int _IF = 50;
String kString = Integer.toString(_IF);
String _IF2 = Integer.toString(_IF);
record.append("_IF");
int _OF = 50;
String lString = Integer.toString(_OF);
String _OF2 = Integer.toString(_OF);
record.append("_OF");
int NA4 = 000;
String mString = Integer.toString(NA4);
String NA42 = Integer.toString(NA4);
record.append("NA4");
int SERIAL = 12345;
String oString = Integer.toString(SERIAL);
String SERIAL2 = Integer.toString(SERIAL);
record.append("SERIAL");
int NA5 = 000;
String nString = Integer.toString(NA4);
String NA52 = Integer.toString(NA5);
record.append("NA5");
int NA6 = 000;
String qString = Integer.toString(NA6);
String NA62 = Integer.toString(NA6);
record.append("NA6");
int STATUS = 000 + j % 001;
String rString = Integer.toString(STATUS);
String STATUS2 = Integer.toString(STATUS);
record.append("STATUS");
int PVV=000;
String sString = Integer.toString(PVV);
String PVV2 = Integer.toString(NA2);
record.append("PVV");
double PVI=00.0;
String tString = Double.toString(PVI);
String PVI2 = String.valueOf(OPI);
record.append("PVI");
double PKW=00.0;
String uString = Double.toString(PKW);
String PKW2 = String.valueOf(PKW);
record.append("PKW");
double PKWH=00.0;
String vString = Double.toString(PKWH);
String PKWH2 = String.valueOf(PKWH);
record.append("PKWH");
record.append((d_f.format(cal.getTime()))+", "+tf.format(cal.getTime()));
int Device_id=101;
addToBuffer(record, Device_id);
record.append("\n");
cal.add(Calendar.MINUTE, ADD_MINUTES);
records.add(record.toString());
record.delete(0, record.length());
addToBuffer(record,OPV);
addToBuffer(record,IKW);
addToBuffer(record,OKW);
addToBuffer(record,OPI);
addToBuffer(record,IPI);
addToBuffer(record,NA1);
addToBuffer(record,BVV);
addToBuffer(record,BVI);
addToBuffer(record,NA2);
addToBuffer(record,NA3);
addToBuffer(record,IPV);
addToBuffer(record,_IF);
addToBuffer(record,_OF);
addToBuffer(record,NA4);
addToBuffer(record,SERIAL);
addToBuffer(record,NA5);
addToBuffer(record,NA6);
addToBuffer(record,NA6);
addToBuffer(record,PVV);
addToBuffer(record,PVI);
addToBuffer(record,PKW);
addToBuffer(record,PKWH);
record.delete(0, record.length());
record.append(OKW);
record.append(OPI);
record.append(IPI);
record.append(NA1);
record.append(BVV);
record.append(BVI);
record.append(NA2);
record.append(NA3);
record.append(IPV);
record.append(_IF);
record.append(_OF);
record.append(NA4);
record.append(SERIAL);
record.append(NA5);
record.append(NA6);
record.append(STATUS);
record.append(PVV);
record.append(PVI);
record.append(PKW);
record.append(PKWH);
record.append(STATUS);
record.append((d_f.format(cal.getTime()))+", "+tf.format(cal.getTime()));
record.append("\t\t");
record.append(COMMA_DELIMITER);
// int Device_id=101;
addToBuffer(record, Device_id);
record.append("\n");
cal.add(Calendar.MINUTE, ADD_MINUTES);
records.add(record.toString());
String insertTableSQL = "INSERT INTO DBUSER"
+ "(OPV, IKW, OKW ,OPI, IPI,NA1, BVV, BVI,NA2, NA3,IPV, _IF, _OF,NA4 , SERIAL ,NA5, NA6, STATUS ,PVI ,PKW , PKWH) "
+ "VALUES" + "("+ OPV + IKW + OKW + OPI + IPI + NA1 + BVV + BVI + NA2 + NA3 + IPV + _IF + _OF + NA4 + SERIAL + NA5 + NA6 + STATUS+ PVI + PKW + PKWH +")";
// record.append("\t\t");
record.append(COMMA_DELIMITER);
try {
insertRecordIntoDbUserTable();
Connection dbConnection = null;
Statement statement = null;
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
System.out.println(insertTableSQL);
// execute insert SQL stetement
statement.executeUpdate(insertTableSQL);
System.out.println(insertTableSQL);
System.out.println("Record is inserted into DbUser table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
}
}
}
}
private static void addToBuffer(StringBuffer buffer, Object data) {
buffer.append(data);
buffer.append(", ");
}
private static void insertRecordIntoDbUserTable()
{
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
I want to export data from java to mysql db but i am not getting any data, initially i want to print the data in console after that i want to add into a database table .I have done jdbc connectivity.But still its not fetching any data please suggest me something.I am getting data in console but not in format what should i do to make the console data in format and to export data into db.
There is a problem with the SQL statement you create here:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(OPV, IKW, OKW ,OPI, IPI,NA1, BVV, BVI,NA2, NA3,IPV, _IF, _OF,NA4 , SERIAL ,NA5, NA6, STATUS ,PVI ,PKW , PKWH) "
+ "VALUES" + "("+ OPV + IKW + OKW + OPI + IPI + NA1 + BVV + BVI + NA2 + NA3 + IPV + _IF + _OF + NA4 + SERIAL + NA5 + NA6 + STATUS+ PVI + PKW + PKWH +")";
Print out the insertTableSQL string to see what it actually contains.
Also, I think there should be an error message printed by this:
System.out.println(e.getMessage());
Show it to us.
UPDATE
INSERT INTO DBUSER(OPV, IKW, OKW ,OPI, IPI,NA1, BVV, BVI,NA2,
NA3,IPV, _IF, _OF,NA4 , SERIAL ,NA5, NA6, STATUS ,PVI ,PKW , PKWH)
VALUES(2341.70000000000000020.050.090.0401084.50024150500123450000.00.00.0)
As I suspected, the problem is that your string concatenation has resulted in an SQL statement with one long meaningless "value". It is invalid SQL.
The solutions:
Put commas between the values in your concatenation.
Use a PreparedStatement instead of a Statement with ? placeholders, and then use setXxxx to set the query arguments.

Fetch an entire row with jdbc as a List

I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}

having error when inserting multiple value into mysql db table using java

Here is my problem. I have to make a program where I will read data from an excel file and load this data into a table in a database. The table would have the name of the excel file and the fields of the table would be the data that is in the first row of the excel file. I have made the code to read the excel file and create the table with the name that I want. Now I have to insert the values in the table but here I have the error.
The code below is the whole program that I have made.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class readexcel {
public static void main (String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/kainourgia","root", "root");
Statement stmt = con.createStatement();
//String filename = "C:\\Users\\myfiles\\Documents\\test6.xls";
String fullPath = "C:\\Users\\myfiles\\Documents\\test7.xls";
String Path = "C:\\Users\\myfiles\\Documents\\";
String filename = "test7.xml";
String[] parts = filename.split("\\.");
String tablename = parts[0];
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(fullPath);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExcelData(sheetData);
HashMap<String,Integer> tFields = new HashMap();
tFields = parseExcelData(sheetData);
String str = getCreateTable(con, tablename, tFields);
str = fillTable ( con, tablename, tFields);
}
private static void showExcelData(List sheetData) {
// HashMap<String, String> tableFields = new HashMap();
for (int i=0; i<sheetData.size();i++){
List list = (List) sheetData.get(i);
for (int j=0; j<list.size(); j++){
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{
System.out.print(cell.getRichStringCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}
if (j < list.size() - 1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}
#SuppressWarnings({ "unchecked", "unused" })
private static HashMap parseExcelData (List sheetData){
HashMap<String,Integer> tableFields = new HashMap();
List list = (List) sheetData.get(0);
for (int j=0; j<list.size(); j++){
Cell cell=(Cell) list.get(j);
tableFields.put(cell.getStringCellValue(),cell.getCellType());
}
return tableFields;
}
private static String getCreateTable(Connection con, String tablename, HashMap<String, Integer> tableFields){
Iterator iter = tableFields.keySet().iterator();
Iterator cells = tableFields.keySet().iterator();
String str="";
String[] allFields = new String[tableFields.size()];
int i = 0;
while (iter.hasNext()){
String fieldName = (String) iter.next();
Integer fieldType=(Integer)tableFields.get(fieldName);
switch (fieldType){
case Cell.CELL_TYPE_NUMERIC:
str=fieldName + " INTEGER";
break;
case Cell.CELL_TYPE_STRING:
str= fieldName + " VARCHAR(255)";
break;
case Cell.CELL_TYPE_BOOLEAN:
str=fieldName + " INTEGER";
break;
}
allFields[i++]= str;
}
try
{
Statement stmt = con.createStatement();
// try
// {
// System.out.println( "Use the database..." );
// stmt.executeUpdate( "USE kainourgia;" );
// }
// catch( SQLException e )
// {
// System.out.println( "SQLException: " + e.getMessage() );
// System.out.println( "SQLState: " + e.getSQLState() );
// System.out.println( "VendorError: " + e.getErrorCode() );
// }
try
{
String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
String createTableStr = "CREATE TABLE " + tablename + " (" + all + ")";
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
}
}
catch(Exception e)
{
}
return str;
}
private static String fillTable(Connection con, String fieldname, HashMap<String, Integer> tableFields){
Iterator iter = tableFields.keySet().iterator();
Iterator cells = tableFields.keySet().iterator();
String str="";
String[] tousFields = new String[tableFields.size()];
int i = 1;
while (iter.hasNext()){
String fieldName = (String) iter.next();
Integer fieldType=(Integer)tableFields.get(fieldname);
while (cells.hasNext()){
String fieldName1 = (String) cells.next();
Integer fieldType1=(Integer)tableFields.get(fieldName1);
}
tousFields[i++]= str;
}
try
{
Statement stmt = con.createStatement();
System.out.println ( "Use the table");
String all = org.apache.commons.lang3.StringUtils.join(tousFields, ",");
String sql= "INSERT INTO" + fieldname + "VALUES (" +all +")";
stmt.executeUpdate (sql);
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage());
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode());
}
return str;
}
private Statement createStatement() {
return null;
}
}
The error that I get is this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at readexcel.fillTable(readexcel.java:183)
at readexcel.main(readexcel.java:68)
Could anyone help me fix it?
What do I have to do to insert the values in each cell?
Is the command in the insert values right?
You try to access non existing index in tousFields.
You need to declare it as:
String[] tousFields = new String[tableFields.size() + 1];

Pass A resultset outside the While Loop in Java

Hello friends i have this class that is getting values from the database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailAlerts {
public static void main(String[] args) {
SMTPAuthenticator sm = new SMTPAuthenticator();//new class
Connection conn = null;
String AtmName = "";
String AtmBal = "";
String atmsend = "";
String[] bals = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.80:1521:dev9i", "BI", "bi");
Statement st1 = conn.createStatement();
String atms = "select CLR_BAL_AMT, FORACID, ACCT_NAME from gam "
+ "where BACID = 'ATM' and CLR_BAL_AMT < 100000";
ResultSet rs1 = st1.executeQuery(atms);
while (rs1.next()) {
AtmName = rs1.getString("ACCT_NAME");
AtmBal = rs1.getString("CLR_BAL_AMT");
bals = AtmBal.split("\n");
for (int j = 0; j < bals.length; j++) {
atmsend = AtmName + "-" + AtmBal;
//System.out.println(atmsend);
}
}
System.out.println(atmsend);
}catch(Exception ad){
System.out.println(ad);
}
}
}
When I try to print out the variable "atmsend" outside the While loop, it only gives the last value in the database but inside the for loop, all the records from the database are there. How can I have all the records on the database outside the While loop?
If you want to put in the variable atmsend all the values from the database, change this code:
atmsend = AtmName + "-" + AtmBal;
to this, although it is not recommended:
atmsend += AtmName + "-" + AtmBal + "\n";
You could use an ArrayList<String> and add all the values inside it while iterating them, instead of using a String
atmsend = atmsend + AtmName + "-" + AtmBal +"\n";
ArrayList <String> atmsend= new ArrayList<>();
Use Arraylist
while (rs1.next()) {
AtmName = rs1.getString("ACCT_NAME");
AtmBal = rs1.getString("CLR_BAL_AMT");
bals = AtmBal.split("\n");
for (int j = 0; j < bals.length; j++) {
atmsend.add(AtmName + "-" + AtmBal+"\n");
//System.out.println(atmsend);
}
System.out.println(atmsend.toString());
declare atmsend as String array
String[] atmsend = null;
now when you store the value inside the while loop use
atmsend[i] = AtmName + "-" + AtmBal;
to retireve the string results
for(int i=0;i<atmsend.length();i++)
{
SYstem.out.println(atmsend[i]);
}

Categories

Resources