how to use multiple queries in java using jdbc - jdbc

how to use multiple queries in java using jdbc
1.how to use this below query in the method without deleting the already existing query in
method
Insert into item_details(stock_name,temple,quantity)
SELECT a.stock_name, a.temple, SUM(Case when Type='purchase' then quantity else
(quantity*-1) End) AS quantity
FROM purchase_details a
GROUP BY a.stock_name, a.temple
public boolean insertIntimationDetails(StockForm ofform) {
boolean status=false;
PreparedStatement pst=null;
Connection conn=null;
try {
System.out.println("Inside insertIntimationDetails ");
String query=" update purchase_details set intimation_quantity = ? where
temple=? and Stock_name=? ";
System.out.println(query);
conn=getConnection();
System.out.println(query);
pst=conn.prepareStatement(query);
System.out.println(ofform.getIntimationQuantity());
pst.setString(2, ofform.getForTemple());
pst.setString(3, ofform.getStockName());
pst.setLong(1, ofform.getIntimationQuantity());
int rows= pst.executeUpdate();
if(rows>0){
status=true;
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(pst!=null)
pst.close();
if(conn!=null)
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return status;
}

You can make the two SQLs atomic by using something similar to below code. This guarantees all or nothing rule.
public boolean insertIntimationDetails(StockForm ofform) {
boolean status = false;
PreparedStatement pst = null;
Connection conn = null;
Statement stat = null;
try {
System.out.println("Inside insertIntimationDetails ");
String query = " update purchase_details set intimation_quantity = ? where temple=? and Stock_name=? ";
System.out.println(query);
conn = getConnection();
conn.setAutoCommit(false); // Disable Auto Commit
System.out.println(query);
pst = conn.prepareStatement(query);
System.out.println(ofform.getIntimationQuantity());
pst.setString(2, ofform.getForTemple());
pst.setString(3, ofform.getStockName());
pst.setLong(1, ofform.getIntimationQuantity());
int rows = pst.executeUpdate();
if (rows > 0) {
status = true;
}
stat = conn.createStatement();
boolean status2 = stat
.execute("Insert into item_details(stock_name,temple,quantity) SELECT a.stock_name, a.temple, SUM(Case when Type='purchase' then quantity else (quantity*-1) End) AS quantity FROM purchase_details a GROUP BY a.stock_name, a.temple");
if (status && status2) {
conn.commit();
} else {
conn.rollback();
}
} catch (Exception e) {
e.printStackTrace();
conn.rollback();
} finally {
try {
if (pst != null)
pst.close();
if (stat != null)
stat.close();
if (conn != null)
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return status;
}

Related

Domino/Notes nhttp spikes on JDBC query to Informix

When connecting to an Informix server via a Bean (or Jar - I've tried both) in an NSF, the nhttp task it spiking and staying spiked. I do not get this problem if the code is run in Eclipse. Here is what I trigger from an XPage (via a managed bean):
public void InformixSQLRS() {
try {
String url = "jdbc:informix-sqli://IPADDRESSHERE:PORTHERE/db_cra:INFORMIXSERVER=SERVERNAME;user=USERNAME;password=PASSWORD";
Class.forName("com.informix.jdbc.IfxDriver");
conn = DriverManager.getConnection(url);
System.out.println("After getting Driver");
String selectSQL = "SELECT FIRST 10 * FROM RtCSQsSummary ";
String whereSQL = "WHERE startdatetime >= TODAY ";
String orderbySQL = "ORDER BY startdatetime DESC";
String strsql = selectSQL + orderbySQL;
stmt = conn.createStatement();
System.out.println(strsql);
ResultSet rs = stmt.executeQuery(strsql);
System.out.println("after executeQuery");
ResultSetMetaData rsmd = rs.getMetaData();
int ncols = rsmd.getColumnCount();
int i, type;
String s = null;
for (i = 1; i < ncols; i++) {
System.out.println(
rsmd.getColumnLabel(i) + " " + rsmd.getColumnType(i));
}
stmt.close();
rs.close();
conn.close();
} catch (
SQLException e) {
System.out.println("ERROR: failed to connect!");
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
return;
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException se) {
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
System.out.println("Goodbye! (finally)");
}
System.out.println("Last call");
}
I am on DDE Release 9.0.1FP10 SHF81. I have the Informix JDBC driver jdbc-4.10.8.1.jar. I have tried putting it in the Jars element, and importing to WebContent/WEB_INF/lib. This happens on both a Domino server Release 9.0.1FP9HF63 on Linux 2.6.32-696.13.2.el6.x86_64 and my local running Windows 7.
I get this error: Exception in thread "Informix-PreparedStatementCacheCleanupThread". Debugged in DDE and found that "IfxSqliConnectCleaner-Thread-1" was taking up a lot of CPU. Suspending that thread let the CPU count to return to normal.
The process completes, printing the results, and the strings at the end of finally and the block. Closing the browser does not release nhttp.
This matches samples provided to connect to Informix. I'm not sure what is causing it to spike/peg for Domino. Is there something I can do to get the thread to release?

ResultSet doesn't return values for DB2, but it return values if I try to do it manualy

I'm trying to get values from resulset, but it return nothing.
When i'm trying to do it through plain sql it return some values.
List<String> res = new ArrayList<String>();
try {
String query = "SELECT COLUMN_NAME FROM idoc.columns_to_show where user = ? "
+ DAO.DB2_UR_POSTFIX;
Connection connection = Properties.getDocsConnection();
try {
PreparedStatement pr = connection.prepareStatement(query);
try {
pr.setString(1, user.getDomainName());
ResultSet rs = pr.executeQuery();
try {
while (rs.next()) {
res.add(rs.getString("COLUMN_NAME"));
}
} finally {
rs.close();
}
} finally {
pr.close();
}
} finally {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return res;
Don't use column name "user" it is reserved name for DB2 database.
Therefore I couldn't find any result.

Getting oracle table row lock, from application

I am getting oracle table row lock, while using below mentioned method written in DAOImpl only in production server. Its working fine in testing server.
`public boolean inactiveServices(String custUid) {
Session session = null;
try {
session = sessionFactory.openSession();
Long count = (Long) (session.createQuery(
"select count(*) as intcustomeridpk from CustomerRegistrationPOJO t where t.customerRegistrationPK.custUid = '"
+ custUid + "'").iterate().next());
if (count < 1)
return false;
String queryToFetchUserIdPk = "select t.customerRegistrationPK.intCustomerId as intcustomeridpk from CustomerRegistrationPOJO t where t.customerRegistrationPK.custUid = '"
+ custUid + "'";
//Iterator iterator = session.createQuery(queryToFetchUserIdPk).iterate();
String currentCustIntIdPk = (String) session.createQuery(queryToFetchUserIdPk).iterate().next();
System.out.println("currentCustIntIdPk "+currentCustIntIdPk);
Criteria criteria = session.createCriteria(CustUtilsPOJO.class).add(
Restrictions.eq("custUtlilityKey.custUid", currentCustIntIdPk))
.add(Restrictions.eq("ynActive", "Y"))
.add(Restrictions.ne("dmlFlag", 2));
List<CustUtilsPOJO> foundUtilList = criteria.list();
for (CustUtilsPOJO eachUtil : foundUtilList) {
System.out.println("centerCode=="+eachUtil.getCenterCode()+"serviceId=="+eachUtil.getCustUtlilityKey().getUtilNumber()+"utilityId=="+eachUtil.getCustUtlilityKey().getUtilId()+"intCustUtil=="+eachUtil.getIntCustomerUtlServiceId());
eachUtil.setDmlFlag(2);
eachUtil.setYnActive("N");
session.merge(eachUtil);
}
Transaction txn = session.beginTransaction();
txn.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.flush();
session.clear();
session.close();
}
}
return true;
}`

jTable that will listen to jDateChooser's 'textfield'?

Hello everyone I'm trying to make a scheduling system for my System and Analysis Design thesis and I am having trouble trying to connect/bind/make the jTable listen to the jDateChooser's input. Elaborately, I want my scheduling to be like this:
I choose a date in the jDateChooser
jTable will 'sort out' itself via the date inputted on the jDatechooser
is there anyway to do this?
For now all I have is a table propertyChangelistener:
private void sched_tablePropertyChangeListener(java.beans.PropertyChangeEvent evt) {
try{
String calendar = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ?";
ps= conn.prepareStatement(query);
ps.setString(1, calendar);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException ignore) {}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
Somehow when I run my application it doesn't seem to open if that block of code is on it which means I really did do something wrong. Can anyone change or tell me what I should do or where should I start with the jTable listening to the jDatechooser thing?
~Thanks in advance for those who will answer!~
Nevermind, turns out all I had to do was change the jDateChooser's Date Format since it wasn't exactly the same formatting hence I couldn't call anything from the database. If anyone's interested on what I did I'll just leave this here
private void jdcPropertyChange(java.beans.PropertyChangeEvent evt) {
try{
String d1 = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ? order by time,timezone";
ps = conn.prepareStatement(query);
ps.setString(1, d1);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null) {
try { conn.close();
} catch (SQLException ignore) {}
}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
What this does is that everytime I pick on a date from the jDateChooser(named it jdc) the table/database calls that date and sorts it out. Which is what I wanted.

In phoenix for hbase , upsert OOM when insert 90000 row data

Run cmd :
./jsvc64/jsvc64 -pidfile ./log/jsvc.pid -outfile ./log/out.txt -errfile ./log/error.txt -Xmx512m -Djava.util.Arrays.useLegacyMergeSort=true -cp :./tools/lib/:./tools/ com.g2us.hbase.cmdlog.monitor.CmdLogHbase ./
SQL :
UPSERT INTO CMDLOG_20130818(game,roleid,otime,logtype,passport,subgame,cmdid,exception,moreinfo,pname_0,pname_1,pname_2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
upsert 90000 row data,the exception occored.
How to solve it.
Exception in thread "Thread-0" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.reflect.Method.copy(Method.java:143)
at java.lang.reflect.ReflectAccess.copyMethod(ReflectAccess.java:118)
at sun.reflect.ReflectionFactory.copyMethod(ReflectionFactory.java:282)
at java.lang.Class.copyMethods(Class.java:2748)
at java.lang.Class.getMethods(Class.java:1410)
at org.apache.hadoop.hbase.ipc.Invocation.<init>(Invocation.java:67)
at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Invoker.invoke(WritableRpcEngine.java:86)
at $Proxy8.getClosestRowBefore(Unknown Source)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegionInMeta(HConnectionManager.java:1019)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegion(HConnectionManager.java:885)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegion(HConnectionManager.java:846)
at org.apache.hadoop.hbase.client.HTable.finishSetup(HTable.java:271)
at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:211)
at org.apache.hadoop.hbase.client.MetaScanner.metaScan(MetaScanner.java:160)
at org.apache.hadoop.hbase.client.MetaScanner.access$000(MetaScanner.java:54)
at org.apache.hadoop.hbase.client.MetaScanner$1.connect(MetaScanner.java:133)
at org.apache.hadoop.hbase.client.MetaScanner$1.connect(MetaScanner.java:130)
at org.apache.hadoop.hbase.client.HConnectionManager.execute(HConnectionManager.java:383)
at org.apache.hadoop.hbase.client.MetaScanner.metaScan(MetaScanner.java:130)
at org.apache.hadoop.hbase.client.MetaScanner.metaScan(MetaScanner.java:105)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.prefetchRegionCache(HConnectionManager.java:947)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegionInMeta(HConnectionManager.java:1002)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegion(HConnectionManager.java:889)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.locateRegion(HConnectionManager.java:846)
at org.apache.hadoop.hbase.client.HTable.finishSetup(HTable.java:271)
at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:263)
at com.salesforce.phoenix.query.HTableFactory$HTableFactoryImpl.getTable(HTableFactory.java:60)
at com.salesforce.phoenix.query.ConnectionQueryServicesImpl.getTable(ConnectionQueryServicesImpl.java:133)
at com.salesforce.phoenix.execute.MutationState.commit(MutationState.java:227)
at com.salesforce.phoenix.jdbc.PhoenixConnection.commit(PhoenixConnection.java:244)
at com.g2us.hbase.phoenix.HBaseHelper.executeUpdate(HBaseHelper.java:62)
at com.g2us.hbase.cmdlog.io.BaseLogPoster.upsertRow(BaseLogPoster.java:153)
I found the problem and fixed it.
the problem that 's preStat define as class field var ,so that call executeQuery() many time no close it ,then OutOfMemoryError.
error code:
public class F{
PreparedStatement preStat = null;
public ResultSet executeQuery(String sql, Object... args) throws Exception {
ResultSet rsResultSet = null;
Connection conn = null;
Statement stat = null;
try {
conn = HBaseUtility.getConnection();
preStat = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.length; i++) {
preStat.setObject(i + 1, args[i]);
}
}
rsResultSet = preStat.executeQuery();
} catch (Exception e) {
dispos(conn, stat);
Log.error(Log.DB, "queryerror|", e);
throw new RuntimeException("hbase query error");
} finally {
HBaseUtility.release(conn);
}
return rsResultSet;
}
}
fixed code:
public class F{
public ResultSet executeQuery(String sql, Object... args) throws Exception {
ResultSet rsResultSet = null;
Connection conn = null;
Statement stat = null;
try {
PreparedStatement preStat = null; //this var as a class var ,and no close every query .
conn = HBaseUtility.getConnection();
preStat = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.length; i++) {
preStat.setObject(i + 1, args[i]);
}
}
rsResultSet = preStat.executeQuery();
preStat.close(); //must be close.
} catch (Exception e) {
dispos(conn, stat);
Log.error(Log.DB, "queryerror|", e);
throw new RuntimeException("hbase query error");
} finally {
HBaseUtility.release(conn);
}
return rsResultSet;
}
}

Resources