jdbc get generatedKeys along with other data efficieintly - jdbc

After batch insert a number of rows, I wish to retrieve the generated keys along with their corresponding inserted rows. how do I do this efficiently? Naively I can use statement.getGeneratedKeys() to query the database for each row based on each generated id, but that seems slow. the code below does a batch insert and then go through all the results in the table, however I don't want to include data that already exists in the table prior to insertion.
is there an alternative?
public static void main(String[] args) throws Exception {
Connection conn = getMySqlConnection();
ResultSet rs = null;
Statement stmt = null;
try {
conn = getMySqlConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
conn.setAutoCommit(false);
stmt.addBatch("INSERT INTO survey(id, name) VALUES('11', 'Alex')");
stmt.addBatch("INSERT INTO survey(id, name) VALUES('22', 'Mary')");
stmt.addBatch("INSERT INTO survey(id, name) VALUES('33', 'Bob')");
int[] updateCounts = stmt.executeBatch();
System.out.println(updateCounts);
conn.commit();
rs = stmt.executeQuery("SELECT * FROM survey");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
System.out.println("id="+id +" name="+name);
}
}
catch(BatchUpdateException b) {
System.err.println("SQLException: " + b.getMessage());
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor error code: " + b.getErrorCode());
System.err.print("Update counts: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
}
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor error code: " + ex.getErrorCode());
}
catch(Exception e) {
e.printStackTrace();
System.err.println("Exception: " + e.getMessage());
}
finally {
rs.close();
stmt.close();
conn.close();
}
}

You have a list of IDs you are interested in. You can use the 'id in (...,...,)' constraint:
StringBuilder newIds = new StringBuilder();
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
if (newIds.length() > 0) newIds.append(',');
newIds.append(rs.getInt(1));
}
if (newIds.length() > ) {
rs = stmt.executeQuery("SELECT * FROM survey where id in ("+newIds+")");
...
}

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?

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;
}`

What is the best way to get the max id of table?

What is the best way to get the max id of table? Below I have paste the error and code. So I was planning on using afterLast() method to get the max id but I get an error.
ERROR:
SQLException: feature not supported
Code:
public class ex03 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave_000/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/T_01_JDBC_01.accdb";
Connection con;
// Get Max ID
Statement stmt0;
String query0 = "select * from user";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "", "");
stmt0 = con.createStatement();
// Get last ID
ResultSet rs = stmt0.executeQuery(query0);
rs.afterLast();
int maxID = rs.getInt("ID");
System.out.println(maxID);
pstmt1.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
It is much more efficient to use SQL to find the maximum value:
select max(id) from user

Sorting item from JComboBox

I'm having problem sorting my items from jcombobox, here are my codes.
public void fillCombo()
{
String dataSourceName = "CheckWriterDB";
String dbURL = "jdbc:odbc:" + dataSourceName;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(dbURL, "", "");
st = con.createStatement();
st.execute("select Suppliers from SuppliersTable");
rs = st.getResultSet();
if(rs!=null)
{
while(rs.next())
{
temp = rs.getString(1);
listOfSuppliersCombo.addItem(temp1);
}
}
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("Your error is: " + e);
}
}
Can anybody help me on how to sort the item shown in my JComboBox, data source of the items shown in my combobox is from my DATABASE. Thank you so much.
Use order by in your query to retrieve data ordered from your database
st.execute("select Suppliers from SuppliersTable order by <fields>");
Syntax: http://en.wikipedia.org/wiki/Order_by_(SQL)

-> java.sql.SQLException: Exhausted Resultset

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == jButton1) {
String ab = jTextField1.getText();
String bc = jPasswordField1.getText().toString();
String cd = jTextField2.getText();
String de = jTextField3.getText();
PreparedStatement ps1 = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "hr");
ps = c.prepareStatement("Select User_Name from AdminLogin where Password =?");
ps.setString(1, bc);
rs = ps.executeQuery();
rs.next();
if (ab.equals(rs.getString(1))) {
ps1 = c.prepareStatement("Update AdminLogin SET Date1=?,Time=? WHERE Password=?");
ps1.setString(1, cd);
ps1.setString(2, de);
ps1.setString(3, bc);
int e = ps1.executeUpdate();
JOptionPane.showMessageDialog(this, "Welcome", "Logged In", JOptionPane.INFORMATION_MESSAGE);
//MainMenuAAI mainMenuAAI = new MainMenuAAI();
//setVisible(false);}
} else if (!(ab.equals(rs.getString(1)))) {
JOptionPane.showMessageDialog(this, "<html>YOU ARE NOT A<br>ADMIN</br></html>", "ERROR", JOptionPane.ERROR_MESSAGE);
//AdminLogin admin=new AdminLogin();
//setVisible(false);
}
c.close();
} catch (Exception e) {
System.out.println(e);
}
}// TODO add your handling code here:
}
Everything is working fine in the code. It is executing the code inside
if(ab.equals(rs.getString(1)))
and showing "Welcome" but not d one inside
if(!(ab.equals(rs.getString(1))))
Whenever I enter wrong username or password it shows the error
java.sql.SQLException: Exhausted Resultset
That is correct, because if you enter wrong username or password, NO record will be returned. So, when you use the rs.next(); in this case, it is trying to access the first row of the empty result set! And that is where it is throwing the exception.
You could fix your code like this:
rs = ps.executeQuery();
//rs.next();
int counter=0;
while (rs.next()) {
counter++;
if (ab.equals(rs.getString(1))) {
ps1 = c.prepareStatement("Update AdminLogin SET Date1=?,Time=? WHERE Password=?");
ps1.setString(1, cd);
ps1.setString(2, de);
ps1.setString(3, bc);
int e = ps1.executeUpdate();
JOptionPane.showMessageDialog(this, "Welcome", "Logged In", JOptionPane.INFORMATION_MESSAGE);
//MainMenuAAI mainMenuAAI = new MainMenuAAI();
//setVisible(false);}
}
}
if(counter==0){
JOptionPane.showMessageDialog(this, "<html>YOU ARE NOT A<br>ADMIN</br></html>", "ERROR", JOptionPane.ERROR_MESSAGE);
}

Resources