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));
}
Related
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'm working on this code but it ain't working. I've put another query which is working but not this one. Help will be much appreciated.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) FROM complaints");
if(rs != null)
{
while(rs.next())
{
String cno=rs.getString("C_NO");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}
In your query
SELECT MAX(PHONE) FROM complaints
you are not assigning an alias to the result. These functions usually return random or default column names, so when you perform
String cno=rs.getString("C_NO");
the C_NO column does not exist on the result set.
To fix it, fix your query like this
SELECT MAX(PHONE) as C_NO FROM complaints
With as C_NO I am giving this column the alias name you are trying to get.
Your select part of the query does not have C_NO , If you need max phone then your query will be:
SELECT MAX(PHONE) as max_phone FROM complaints
assuming that phone is long your complete code will be :
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) as max_phone FROM complaints");
if(rs != null)
{
while(rs.next())
{
Long cno=rs.getLong("max_phone");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}
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 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.
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);
}
}
}