i am fetching all data from database and stored the resultset to a list. but could not fetch all data. i want to store the data in a dropdownlist. My code is bellow.
public static void updateChallan(){
ChallanNumber pd=null;
int i=0;
String customerName="";
List<ChallanNumber> challanList= new ArrayList<ChallanNumber>();
Connection con = DB.getConnection();
try
{
String st="select CHALLAN_NUMBER,CUSTOMER_CODE,CHALLAN_DATE from DELIVERY_CHALLAN_DETAILS order by CHALLAN_NUMBER";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(st);
while(rs.next())
{
String stCustName="select CUSTOMER_NAME from CUSTOMER_DETAILS where CUSTOMER_CODE='"+rs.getString(2)+"'";
Statement stmtCustName=con.createStatement();
ResultSet rsCustName=stmtCustName.executeQuery(stCustName);
while(rsCustName.next()){
customerName=rsCustName.getString(1);
}
customerName=rsCustName.getString(1);
//System.out.println(customerName +" "+i);
pd=new ChallanNumber(rs.getString(1),customerName,rs.getString(3));
challanList.add(i,pd);
i++;
}
}
catch(Exception e)
{
//e.printStackTrace();
}
render(challanList);
}
Dropdownlish code is in bellow.
<select name="challanNumber" id="challanNumber">
<option value="selected" selected="selected">ChallanNumber-CustomerCode- Date</option>
#{list challanList, as:'cl'}
<option value="${cl.challanNumber}">${cl.challanNumber}(${cl.customercode}-${cl.challanDate})</option>
#{/list}
</select>
The problem is that you are not closing the Connection and ResultSet when you get an exception. And so the database has exhausted all open cursors.
You need to close everything you open, it means statement, resultsets. You do that in the finally part of your try/catch to ensure things are correctly closed.
When you close a statement, the resultset linked to that statement is closed too.
public static void updateChallan() throws Exception {
ChallanNumber pd = null;
int i=0;
String customerName = "";
List<ChallanNumber> challanList= new ArrayList<ChallanNumber>();
Connection con = DB.getConnection();
Statement stmt = null;
try {
String st = "select CHALLAN_NUMBER,CUSTOMER_CODE,CHALLAN_DATE from DELIVERY_CHALLAN_DETAILS order by CHALLAN_NUMBER";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(st);
while (rs.next()) {
String stCustName = "select CUSTOMER_NAME from CUSTOMER_DETAILS where CUSTOMER_CODE='" + rs.getString(2) + "'";
Statement stmtCustName = con.createStatement();
try {
ResultSet rsCustName = stmtCustName.executeQuery(stCustName);
while (rsCustName.next()){
customerName = rsCustName.getString(1);
}
} finally {
if (stmtCustName != null)
stmtCustName.close();
}
customerName = rsCustName.getString(1);
//System.out.println(customerName +" "+i);
pd = new ChallanNumber(rs.getString(1), customerName, rs.getString(3));
challanList.add(i, pd);
i++;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
}
render(challanList);
}
Besides, you should read the docs of PlayFramework (here for Play2) there are database stuff to avoid using ResultSets and Statements directly, dealing with higher structures like domain objects, the framework will do the rest for you.
Related
I have a complex directory system with millions of xml files which i need to retrieve to an XMLType column in Oracle 18c. I'm working with a java method that is executed by a procedure to re-load this files on this particular table. Since a lot of the of the java libraries were deprecated i'm out of options to solve this issue. The way I had finded to workaround was a tempory table with a CLOB column where I can insert the content from the files and than inside oracle I insert those in the original table using a XMLType(clobVariable). BUT, it doesnt work on files larger then 20k characters.
If anyone can help me I'm more than glad to give more information.
(I'm from Brazil and maybe I didn't made myself clear on the explanation btw)
public static void inserirXml() throws Exception{
try {
int num_id_nfe;
String dirArquivo = "";
String query;
String queryUpdate;
String reCheck, insert;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
conn.setAutoCommit(false);
query = "SELECT ID_NFE, DSC_CAMINHO_XML FROM DFE_NFE_CAMINHO_XML WHERE FLG_CARREGADO = 0 AND ROWNUM <= 1000";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
stmt.executeQuery(query);
ResultSet rset = stmt.getResultSet();
while(rset.next() == true) {
try {
num_id_nfe = rset.getInt(1);
dirArquivo = rset.getString(2);
byte[] bytes = Files.readAllBytes(Paths.get(dirArquivo));
String xmlString = new String(bytes, "utf-8");
String insertQuery = "INSERT INTO DFE_NFE_REP_XML_TMP (ID_NFE, XMLCLOB) VALUES(?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
xmlString = xmlString.substring(1);
pstmt.setInt(1, num_id_nfe);
pstmt.setNString(2, xmlString);
pstmt.execute();
pstmt.close();
queryUpdate = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 1 WHERE ID_NFE = " + num_id_nfe + " \n";
stmt2.executeQuery(queryUpdate);
}catch(SQLException e) {
System.err.println(e.getMessage()+" loop");
stmt2.close();
throw e;
}
}
insert = "INSERT INTO DFE_NFE_REP_XML (ID_NFE, CONTEUDO) SELECT ID_NFE, XMLType(XMLCLOB) FROM DFE_NFE_REP_XML_TMP";
stmt4.executeUpdate(insert);
reCheck = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 0 WHERE id_nfe not in (select id_nfe from dfe_nfe_rep_xml) and flg_carregado = 1";
stmt3.executeQuery(reCheck);
conn.commit();
rset.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
conn.close();
} catch (SQLException x) {
System.err.println(x.getMessage()+" geral");
}catch (ClassNotFoundException y) {
throw y;
}catch(Exception z) {
throw z;
}
}
I am trying to execute a query that returns a student whose name and last name concatenated equal the search key parameter.
For that I am doing this in my class that manages anything related to the database for my Student class.
When the query is executed I am getting the error that follows:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
What's wrong? I have checked that's the correct way to use concat.
name and lastName are VARCHAR in the mysql database.
public static Student findStudent(String key) {
if (key == null) return null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
String selectSQL = "select * from project.students where concat(name, lastName) = ? ;";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, key);
Student student = null;
rs = preparedStatement.executeQuery(selectSQL);
if (rs.next()) {
StudentDB.setStudentAttributes(student, rs);
}
return student;
} catch(SQLException e) {
e.printStackTrace();
} finally {
close();
try {
if (preparedStatement != null) preparedStatement.close();
if (rs != null) rs.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
return null;
}
Your problem is that you prepare the statement with
preparedStatement = dbConnection.prepareStatement(selectSQL);
which is correct, but then when you try to execute the PreparedStatement you supply the selectSQL string again:
rs = preparedStatement.executeQuery(selectSQL);
That is incorrect. You've already prepared the statement, so when the time comes to execute it you just do
rs = preparedStatement.executeQuery();
I am not able to run code below with multiple select query. I am able to run queries below individually but I want to run all together and store their results in ArrayList. Error I get is java.sql.SQLException: ResultSet not open. Operation 'next' not permitted. Verify that autocommit is off.
Any advice? or is there a better way to do this? Thanks
public ArrayList<String> getTotalCountBasicQueries() {
ArrayList<String> totalCount = new ArrayList();
Statement stmt = null;
stmt = conn.createStatement();
conn.setAutoCommit(false);
try {
String q1 = "select count query";
String q2 = "select count query2";
String q3 = "select count query3 ";
ResultSet rs = stmt.executeQuery(q1);
ResultSet rs2 = stmt.executeQuery(q2);
ResultSet rs3 = stmt.executeQuery(q3);
while (rs.next()) {
totalBasicCount.add(rs.getString(1));
}
while (rs2.next()) {
totalCount.add(rs2.getString(1));
}
while (rs3.next()) {
totalCount.add(rs3.getString(1));
}
rs.close();
rs2.close();
rs3.close();
stmt.close();
} catch (Throwable e) {
System.out.println("Table fetch failed or result data failed");
} finally {
if (stmt != null) {
try {
stmt.close();
System.out.println("Could not close query");
} catch (SQLException ex) {
System.out.println("Could not close query");
}
}
return totalBasicCount;
}
}
}
See the javadoc for ResultSet :
A ResultSet object is automatically closed when the Statement object
that generated it is closed, re-executed, or used to retrieve the next
result from a sequence of multiple results.
you can't have multiple resultset open for a unique statement, per spec. however, some jdbc driver allow this
try :
ResultSet rs = stmt.executeQuery(q1);
while (rs.next()) {
totalBasicCount.add(rs.getString(1));
}
ResultSet rs2 = stmt.executeQuery(q2);
while (rs2.next()) {
totalCount.add(rs2.getString(1));
}
ResultSet rs3 = stmt.executeQuery(q3);
while (rs3.next()) {
totalCount.add(rs3.getString(1));
}
I having problem with my code:
ERROR: ORA-01000: maximum open cursor exceeded. This code is called from multiple threads.
Q. is oracle cursors are differen than JDBC cursor(resultset)?
public static void viewTable(Connection con, String TBName)
throws SQLException {
Statement stmt = null;
String query = "select *from " + TBName;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String studentName = rs.getString("STD_NAME");
System.out.println(studentName + "\t");
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { stmt.close(); }
}
}
Use try-with-resources to ensure that both statement and result set are closed.
String query = "select STD_NAME from " + TBName;
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
String studentName = rs.getString("STD_NAME");
System.out.println(studentName + "\t");
}
} // Closes rs and stmt even with exceptions.
You should always close the ResultSet and the Statement. As you said, your code is accessed by many thread so a lot of Resultset will be open and never
closed.
Put the ResultSet variable out of the try catch block and close it in a finally, beside the Statement closing.
I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.
I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
Use aliases:
SELECT COUNT(*) AS total FROM ..
and then
rs3.getInt("total")
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
I have done it this way (example):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r#r.com"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}