Interface ResultSet
I am now confused with interface and class. java.sql.Resultset is an interface as defined in spec. However, we can always use its methods. So who implement those methods? According to the definition of interface, the methods are not implemented.
Thanks!
Do this
ResultSet rs = pstmt.executeQuery(sql);
System.out.println("ResultSet class = " + rs.getClass());
You will see that rs is not a 'ResultSet' rather it is a class which implements a ResultSet.
Similar Messages
-
hi
ResultSet is an interface and any one who uses it must provide implementation to it.
but in our programs
we write
ResultSet rs=stsme.execute() like this and we use
rs.getString()
rs.getInt()
here we r using the methods directly without implementing it
then my question is
who implement these methods for u?
thank sin advanceThe concrete implentation of the SQL interfaces, ResultSet, Connection, Statement etc. are part of the database driver (JDBC) package. A different implementation goes with each database driver; mySql, postgress, oracle etc..
-
About Connection, ResultSet, Statement interfaces....
hi ,
Connection, ResultSet, Statement etc.. all are the interfaces. But when i am writing the codes like,
Statement stmt= con.createStatement();
ResultSet rs= stmt.excuteQuery("select * from student_mst");
where con is the instance of Connection interface.
Therefore my question is that since all those(Connection,ResultSet,Statement) are interfaces then how the methods createStatement(),excuteQuery(String sql) are being executed where as those methods are only the declarations in those interfaces,nothing else.ok.......
So can u tell me in this case, actualy which class is
implenting the Statement interface such that
"executeQuery(String)" is working properly.....??????Hello,
First you need to understand interface and its working.. I will write one example code for u and I think this may hel how Connection, Statement and ResultSet work
This is out main Class
public class Main {
public static void main(String[] args) {
Connection con = DriverManager.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("My Query");
rs.getString();
}Connection.java
public interface Connection {
public Statement createStatement();
}Statement.java
public interface Statement {
ResultSet executeQuery(String sql);
}ResultSet.java
public interface ResultSet {
public String getString();
}DriverManager.java
public class DriverManager {
public static Connection getConnection() {
System.out.println("Calling getConnection()...");
return new ConnectionImpl();
}Following are the implementstions of the interfaces
ConnectionImpl.java
public class ConnectionImpl implements Connection {
public Statement createStatement() {
System.out.println("Calling createStatement()...");
return new StatementImpl();
}StatementImpl.java
public class StatementImpl implements Statement{
public ResultSet executeQuery(String sql) {
System.out.println("Calling executeQuery()...");
return new ResultSetImpl();
}ResultSetImpl.java
public class ResultSetImpl implements ResultSet{
public String getString() {
System.out.println("Calling getString()...");
return "My String";
}And the Output is
Calling getConnection()...
Calling createStatement()...
Calling executeQuery()...
Calling getString()...
I suppose now you can understand how the Connection, Statement and ResultSet interfaces work -
Problem in displaying XML document from database
Hi I am getting only record in printing xml file which takes from data base.
Here is my programme.
Document doc;
����public void processTable(Connection con, String tableName)
����{
��������try
��������{
������������this.iColumnCount=0;
������������HashMap hm = new HashMap();
������������//XML related Interfaces
������������DocumentBuilderFactory dbf;
������������DocumentBuilder db;
������������Element rootElement = null;
Element colData = null;
������������Element relElement = null;
�����
������������//Database relevent Interface
������������ResultSet rslt = null;
������������DatabaseMetaData dmd = null;
������������ResultSetMetaData rsmd= null;
������������//Initilize the Factory Classes
������������dbf = DocumentBuilderFactory.newInstance();
������������db = dbf.newDocumentBuilder();
������������doc = db.newDocument();
������������//Assign the root elements to document
������������rootElement = doc.createElement("entity");
colData = getColMetaData(tableName);
������������rootElement.appendChild(colData);
������������doc.appendChild(rootElement);
������������TransformerFactory tFactory = TransformerFactory.newInstance();
����������������Transformer transformer = tFactory.newTransformer();
����������������transformer.transform(new DOMSource(doc),
��������������������new StreamResult(new FileOutputStream(tableName+".xml")));
��������} catch (Exception sqle)
��������{
����������������e.printStackTrace();
��������}
����}
����/**
�����* Method getColMetaData.
�����* @param tableName
�����* @return Element
�����*/
����private Element getColMetaData(String tableName)
����{
��������try{
������������ResultSet rslt = null;
������������ResultSetMetaData rsmd = null;
������������DataTypeMap dtp = new DataTypeMap();
������������HashMap hm = new HashMap();
������������hm = dtp.DataTypes();
������������Connection con = db.createConnection();
������������Statement stmt = con.createStatement();
������������String sQuery = "select * from " +tableName;
������������rslt = stmt.executeQuery(sQuery);
������������rsmd = rslt.getMetaData();
������������Element rooElement = null;
������������//Element currentElement =null;
������������iColumnCount = rsmd.getColumnCount();
����������������Element currentElement = null;//doc.createElement("field");
// rootElement = doc.createElement("column");
����������������for (int i = 1; i <= iColumnCount; i++)
��������������������{
currentElement = doc.createElement("field");
������������������������currentElement.setAttribute("DBFieldName",rsmd.getColumnName(i));
������������������������currentElement.setAttribute("FieldName",rsmd.getColumnLabel(i));
������������������������
��������������������}
��������������return currentElement;
��������catch(Exception ee){
������������logger.info(ee.getMessage());
��������}
��������return null;
����}
Here 'return currentElement;' return the collection of elements.But when I print
document it is giving only last element.I am not getting how only one record is printing even it has more records
please help me in this regards.
here the out put:
<?xml version="1.0" encoding="UTF-8"?>
<entity>
��<field DBFieldName="X_TYPE" FieldName="X_TYPE"/>
</entity>
-krish
[email protected]Problem in displaying the XML Data from database
Hi I have requirement of generating the XML from database.I could able to acheive partially.
I am giving the problem below.
public void processTable()
Element rootElement = doc.createElement("entity");
Element colData= getColMetaData(tableName);
rootElement.appendChild(colData);
doc.appendChild(rootElement);
//print the document
/*getColData method as follows*/
private Element getColMetaData(String tableName)
try{
ResultSet rslt = null;
ResultSetMetaData rsmd = null
Connection con = db.createConnection();
Statement stmt = con.createStatement();
String sQuery = "select * from " +tableName;
rslt = stmt.executeQuery(sQuery);
rsmd = rslt.getMetaData();
iColumnCount = rsmd.getColumnCount();
Element currentElement = doc.createElement("field");
for (int i = 1; i <= iColumnCount; i++)
currentElement.setAttribute("FieldName",rsmd.getColumnName(i));
currentElement.setAttribute("Position", parseString(i));
rootElement.appendChild(currentElement);
return currentElement;
catch(Exception ee){
logger.info(ee.getMessage());
return null;
/* End of Method*/
Here when I printing the document it is giving out put like :
<entity >
<field FieldName="X_ID" Position="1"/>
</entity>
The is displaying only one field information even though table contains more then one column.If we maintain all the aboue code in single method it is working fine.I want to decouple the like above.Bcz I may have more then one set of elements like this.
Please help in this regards,
-Krish
[email protected] -
Do v need to Close the Connection
Hi plz tel me
1. Do v need to Close the Database Connection ?
2. which is better to use Statement or ResultSet Interface ?
Thanx in AdvanceHi plz tel me
1. Do v need to Close the Database Connection ?
2. which is better to use Statement or ResultSet
Interface ?
Thanx in AdvanceHi sumit.manhas,
For your info, refer these links....
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlpublic interface Statement
The object used for executing a static SQL statement and returning the results it produces.
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlpublic interface ResultSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
Regards,
JavaDriver -
Urgent: How to map existing java classes
I created an IDL file where I want to use java.sql.ResultSet. The line is:
module CMS {
interface Comm {
ResultSet search(in string searchString);
The ResultSet has to be the ResultSet as in java.sql.ResultSet. I tried to add the following code:
module java {
module sql {
interface ResultSet {
but it doesn't work. Who can help me?I think that you can try the type "Any"
Then after the client receive the any object it can be cast to the object you have. -
try
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Test;User=usr;Password=secret");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String insertData = "Select * from users where UserID='123456'";
ResultSet rs = stmt.executeQuery(insertData);
rs.updateString("Name","Ashish");
//rs.updateString("UserID","yyyasb3");
rs.updateString("Dept","ACCT");
rs.updateString("Aprv_Lvl","03");
rs.updateString("Pwd","secret");
rs.updateRow();
catch(Exception ex)
out.println("The Exception is"+ex);
The above code gives me a SQL Exception: Invalid operation for the current cursor positionFrom the FIRST FEW sentences of the ResultSet API...
public interface ResultSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. -
I have create a classA called
ResultSetTableMode extends DefaultTableMode
in another classB
rs = stat.executeQuery(query);
model = new ResultSetTableModel(rs);
JTable table = new JTable(model);
there is nothing printed on the screen
but adding followings in classB
model.addRow(new Object[]{});
if the query have 3 rows
add the above code 3 times
the result shown on the JTable
I want to add the 4th row on the JTable with null value
exceptions are thrown
How to fix it ??import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestTable extends JFrame {
private JTable table;
public static void main(String args[]) {
try {
TestTable frame = new TestTable();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
public TestTable() {
super();
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
table = new JTable(new ResultSetTableModel(new SpecialResultSet()));
scrollPane.setViewportView(table);
class ResultSetTableModel extends DefaultTableModel {
private ResultSet results;
public ResultSetTableModel(ResultSet set) {
Vector headers = new Vector();
headers.add("Column 1");
setDataVector(convertSetToVector(set), headers);
private Vector convertSetToVector(ResultSet set) {
Vector master = new Vector();
while (set.hasNext()) {
Vector row = new Vector();
row.add(set.next());
master.add(row);
return master;
class SpecialResultSet implements ResultSet {
List results = new ArrayList();
Iterator iter;
public SpecialResultSet() {
results.add("one");
results.add("two");
iter = results.iterator();
public Object next() {
return iter.next();
public boolean hasNext() {
return iter.hasNext();
public int getCount() {
return results.size();
interface ResultSet {
public Object next();
public boolean hasNext();
public int getCount();
} -
Implementation of java.sql.* abstract methods
Hi to u all,
Can someone tell me where the abstract methods in some interfaces in the java.sql package are implemented?
For example:
-- START CODE --
ResultSet rs = null;
try
ps = db().prepareStatement("select * from aTable where x=?");
ps.setInt(1, aValue);
rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
-- END CODE --
It's about the getMetaData()-call.
It returns information about the column names in the resultset.
If I open the declaration (eclipse) the abstract method getResultSet() in the interface ResultSet in the java.sql-package is shown.
So where is the actual implementation of the method??
As a collegue told me he suspected the implementation is probably somewhere in the driver-software. If this is the case, how does the JVM know to find it there?
Thx in advance for your time and answer(s)The JDBC driver implements the JDBC API.
The JVM how to know that?
1. The Class.forName("jdbc driver name") will load the driver into memory.
2. The DriverManager.registerDriver(Driver driver) will register the driver for later use.
Check the DriverManager.java for more detail. -
Statement and ResultSet Interface type of Object
Hi,
Can any one explains me where exactly (in which Class) the implementation of the Statement and ResultSet Interface type of Object Instance be created
Regards
KrishnaI dont really understand what you are trying to ask but:
Your JDBC driver has concrete implementations of Statement and Resultset. If you want to know what classes are being used try something like:Connection con = ??;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "???" );
System.out.println( "Connection class: " + con.getClass().getName() );
System.out.println( "Statement class: " + st.getClass().getName() );
System.out.println( "ResultSet class: " + rs.getClass().getName() ); -
Hi all,
In JDBC, statement, Resultset, CallableStatement, PreparedStatement interfaces there.
My question is, why they are interfaces but not classes.
If anybody knows, pl. answer to my question.
Thanx and regrads,
srinivasThey are interfaces because they need to be implemented differently (possibly) by each creator of a JDBC driver. The class that does the work for a PreparedStatement in the Sun ODBC-JDBC driver is not the same one that does the work for a PreparedStatement for the Oracle thin client driver.
-
Interfaces / Abstract classes / ResultSets
I want to set the fetch size of each java.sql.ResultSet throughout my application, in one place. ResultSet is an interface and a ResultSet is returned by a call to PreparedStatement.execute(). So I figured I could implement ResultSet in an abstract class of my own and just override getFetchSize() or put a setFetchSize() in the constructor. Anyway, it seems I get a ClassCastException when casting the ResultSet returned from PreparedStatement.execute() to MyResultSet:
java.lang.ClassCastException: oracle.jdbc.driver.OracleResultSetImpl
I've tried having MyResultSet implement oracle.jdbc.driver.OracleResultSet too just in case. But no luck there either. If I try and implement OracleResultSetImpl I'm told it's not public and so can't be accessed from outside the package.
Can I do this somehow? Or an alternative, simple way?I want to set the fetch size of each
java.sql.ResultSet throughout my application, in one
place. ResultSet is an interface and a ResultSet is
returned by a call to PreparedStatement.execute(). So
I figured I could implement ResultSet in an abstract
class of my own and just override getFetchSize() or
put a setFetchSize() in the constructor.Yes, you can.
Anyway, it
seems I get a ClassCastException when casting the
ResultSet returned from PreparedStatement.execute()
to MyResultSet:Well, you have to re-implement PreparedStatement as well, otherwise of course it won't even know that your class exists, let alone use it.
Serializabe z = method();
If I define method() to return a String, it doesn't mean that it'll suddenly return something else simply because I wrote it and it also implements Serializable.
java.lang.ClassCastException:
oracle.jdbc.driver.OracleResultSetImplThe object you get is simply not an instance of your class.
Simple way around: create a wrapper class around the original ResultSet that does what your implementation did. -
Can Vector contain ResultSet which is a Interface
What i am trying is to execute 3 different SQL in a Bean and try it to transfer in a JSP.I am using Vector for this work.I am putting the ResultSet in the Vector and transfer that Vector to the Jsp,In which i am displaying the Result.
I wanted to know that Is it possible to do the thing in this way.Or some other way is there.
Could any one tell me the Solution.May be I 'm wrong, but the objets implementing the ResultSet interface
must be serializable and have a public default constructor if you want
to serialize/deserialize them. I don't think the most know drivers
are offering you these features.
Even if it's feasible, I don't think serializing a whole data set is
really a good idea, because of the big overhead of doing this.
You'd better convert the resultSet into smaller objects and
only pass a set of them to your jsp only under request,
not the whole thing once.
Hope this helps -
Implementation for Resultset interface
Hi,
We are developing a JCA adapter where we have to implement the java.sql.ResultSet Interface as per the JDBC 3.0 Spec.I want to know ho the values retrieved from database are stored into the ResultSet by the JDBC Drivers.Can i get a sample source code for this implementation.I am connecting to database with a native C code and the C code is returning the result in a data structure ex Map.I want to set this result in a ResultSet before returning it to the client.
And I have the mySQL JDBC Driver implementation source code with me and as per our requirement its not complete. So anyone can shed som light on this.
regards
K.Sreenivasknow ho the values retrieved from database are stored into the ResultSet by the JDBC DriversHowever you want. All it is an interface, so you can do it however you want.
I don't know of any examples that store it 'in' the ResultSet. They all use the underlying protocol to 'store' it.
You can get the jdbc-odbc bridge source comes with the jdk source (at the JDC site.)
The RmiJdbc proxy comes with source - http://www.objectweb.org/
The freetds driver has source - www.freetds.org -
Does anyone know if there is a way of creating one result set from two?
I need to write a query to return results from two databases that can not talk to each other (!). The results are only seen after some java fantasticness has turned them into an excel spreadsheet using POI. I'm using a class I wrote that takes the ResultSet data and turns this into an excel spreadsheet. As I already have this class, I'd rather use it than write something new.
Basically however I look at it I get two ResultSet objects. I have three options - either find a way to merge the ResultSets (which I like the sound of, but can find no easy method to do this), use one of the ResultSets to write the sheet (leaving gaps) and fill in the gaps with the data from the other ResultSet, or write lots of new stuff that does this in another way.
Incidentally, whilst looking through the API (java 1.3, so depressing to be so backwards!) I cannot find an implementing class of the ResultSet interface. Obviously one must exist... but where is it and what is it called (as while I'm happy to consider extending this as an option, implementing all the methods of the interface sounds like a time-consuming struggle and a tremendous bore to boot!)??The dbs are of two different types (Sybase and Oracle) and are both huge.
Also the db team is based mainly in Pune, India, so while they are very good at what they do, we are seperated by their general belief that they understand what I'm saying. As we're miles from them (London) I can't tell them what I want them to do with any degree of confidence in their accuracy at following my instructions. Basically I'm preempting human errors, and also have no idea how you would start connecting the two different dbs (If I cared about that sort of thing, I'd be a DBA).
I don't know hwat your experience of dealing with dedicated DBA's is, but mine is that if I have to rewrite this part of the program (so far a month and a half has been spent on this part), it will still be quicker than getting any major change done to an existing and robust db, let alone two. The amount of other systems that would have to be altered (albiet in a minor way) would be significant too. Of course, not being a DBa I'm probably missing a very quick easy way of effecting this change without these problems, but I generally find it easier to stick to what I know.
Maybe you are looking for
-
Hello, I upgraded to iOS6 tonight on my 4s via wifi and noticed that I am unable to change the volume of music/calls/ringer/videos via the volume buttons and the volume slider does not appear in the music or video apps..I am aware that a similar issu
-
How to search a network/external hard drive in finder?
I use my Macbook at work where I am required to save all files I work on to a network hard drive on our server. I also have to be able to find and access files from the network drive for customers. In Snow Leapord I had the ability to type in the sea
-
[Solved] Greek accented characters and Qt Applications
Hello. This is my first day with Arch linux. My problem has to do with greek accented characters like ά, ή, ό etc. I can type these characters on my browsers, rox file manager and other applications but not on Qt based applications like Skype and TeX
-
Lost my Calendar after crash iPhoto 6.0.1
I spent a few hours making a two year calendar, but when it was almost finished iPhoto got stuck when I tried to add another photo to the calendar list. After watching the beachball for several minutes I force quit iPhoto. When I relaunched it, I was
-
SAP screen is displayed in ITS mobile
Hi friends, I am new to ITS mobile. I am getting 2 errors The error is given below. 1. ITS mobile displays SAP screen. 2. ITS_REFERENCE_NULL: Template "itsmobile\99\rlmenu_2088.html" has caused a runtime error in function "label". Cause of error: Var