I have 2 queries and therefore 2 ResultSet's returned from MySQL in Java through createStatement(). The queries are like
SELECT * FROM abc;
SELECT * FROM def;
These queries are run simultaneously in single createStatement() like
CreateConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
stat.close();
conn.close();
How can I get the next ResultSet returned by second query?
Use Statement#getMoreResults and Statement#getResultSet methods:
ResultSet rs = stat.executeQuery("select * from ABC; select * from DEF;");
while(rs.next()) {
//Iterate through first resultset
}
rs.close();
if (stat.getMoreResults()) {
rs = stat.getResultSet();
while(rs.next()) {
//Iterate through second resultset
}
}
stat.close();
In order that make this method to work, you should add allowMultiQueries=true property to your connection by appending this property to your connection url:
String url = "jdbc:mysql://yourServer:yourPort/yourDatabase?allowMultiQueries=true";
Note that you can perform multiple queries per Statement using a single Connection object:
Connection con = ...
List<String> sqlStatements = ... //a list with all the SELECT statements you have
for (String query : sqlStatements) {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//do your logic here...
}
rs.close();
stmt.close();
}
conn.close();
Related
I'm running java 1.8 connecting to oracle 12c using ojdbc7.jar for jdbc connection.
This is the code that execute to retrieve the data
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt=con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
but the code is not entering the while loop.
When i try exeuction the same query in DB, I could see the table has 10 entries.
Does anyone know what could be the reason?
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt = con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e ) {
} finally {
if (stmt != null) { stmt.close(); }
}
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 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 have this query:
Connection conn = null;
stmt = conn.createStatement();
stmt.execute("SELECT * FROM school.users");
and I got results from that query. If I try to implement this following code in java to set a default database:
stmt.execute("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
I have this error:
Exception-> [Teradata Database] [TeraJDBC 14.10.00.17] [Error 3807] [SQLState 42S02] Object 'users' does not exist
Can You see what is Wrong?
Add DATABASE param in the url and try.
eg. url="jdbc:teradata://exampleDns/DATABASE=school"
I hope this is what you are looking for
Try this:
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
}
catch(SQLException se){
se.printStackTrace();
finally{
stmt.close();
conn.close();
}
What if you use the executeUpdate "method" of the Statement?
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.executeUpdate("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
I want to change the position of the cursor to the first row but I don't know why my code is not working.when I add rs2.first():
and also I am getting this error :
This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).
try{
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
String url = "jdbc:derby://localhost:1527/test";
Connection conn = DriverManager.getConnection(url);
String query = "select * from APP.RANKING";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query);
while (rs.next()){
String BID = rs.getString("BALLOT_ID");
String CN = rs.getString("CANDIDATE_NAME");
String ROID = rs.getString("USER_ID");
Ro1_ID = ROID;
String RA = rs.getString("RANK");
int rowNum = rs.getRow();
int rowNum2;
boolean In_check = false;
while(rs2.next()){
In_ballot.addElement(BID);
}
rs2.First();
In_ballot.addElement(BID);
}
}
catch(Throwable e) {
System.err.println(e.getMessage());
}
this.InB_list.setModel(In_ballot);
By default, calling createStament() in a connection results in every ResultSet having type 'TYPE_FORWARD_ONLY' - This results in the exception you see using first().
Instead, use another versions of createStatement, like this one.
This sample of creating scrollable ResultSets in Derby might help.