presently my method uses basic jdbc concept like this,
public static ArrayList<VehicleDetailsBean>
getAllVehicleDetails(String groupId,String clientId)
throws ClassNotFoundException, SQLException {
ArrayList<VehicleDetailsBean> vehicleDetailsList =
new ArrayList<VehicleDetailsBean>();
try {
Statement statement = connection.createStatement();
String sql ="SELECT a.vehicleno,a.lat,a.lng,a.status, "+
"a.rdate,a.rtime from latlng a,vehicle_details b where"+
"a.vehicleno=b.vehicleno and b.clientid='"+
clientId+"' and b.groupid in(select groupid from group_details"+
" where groupname='"+groupId+"' and clientid='"+clientId+"')";
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
VehicleDetailsBean vehicleDetailsBean=new VehicleDetailsBean();
vehicleDetailsBean.setVehicleno(rs.getString("vehicleno"));
vehicleDetailsBean.setLat(rs.getString("lat"));
vehicleDetailsBean.setLng(rs.getString("lng"));
vehicleDetailsBean.setStatus(rs.getString("status"));
vehicleDetailsBean.setRdate(rs.getInt("rdate"));
vehicleDetailsBean.setRtime(rs.getString("rtime"));
vehicleDetailsList.add(vehicleDetailsBean);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
it returns an ArrayList. Now I want to change it to hibernate SO I will change above code as,
query = session.createQuery(hqlquery);//I am not getting how to write hqlquery
List<Object[]> groupList = query.list();
for(Object[] arr : groupList){
System.out.println(Arrays.toString(arr));
}
by doing this it returns List object but my method has to return ArrayList. So can any one help me to write query and return the result as ArrayList.
You can do it the ugly way:
query = session.createQuery(hqlquery); // Take a walk in Hibernate Docs for HQL Queries
List<?> groupList = query.list();
ArrayList<VehicleDetailsBean> result = new ArrayList<VehicleDetailsBean>(groupList.size());
for (Object o : groupList) {
result.add((VehicleDetailsBean) o);
}
return result;
If you want to return it as ArrayList, you can just addAll it with your ArrayList.
List<VehicleDetailsBean> groupList = (List<VehicleDetailsBean>) query.list();
vehicleDetailsList.addAll(groupList);
return vehicleDetailsList;
You can see similar question here and a way to cast here
EDIT
Or try to add entity
List<LatitudeBean> bean = (List<LatitudeBean>) session.createSQLQuery(query)
.addEntity(LatitudeBean.class).list();
//add to ArrayList here
Related
what I want is to get all the values that are into a column that i call in query from Java to SQL Server, I think it is like this:
public ArrayList createArray(ResultSet data){
try {
ArrayList arrayData = (ArrayList) data.getArray(1);//get all the data from the resultSet that's into the column 1
return arrayData;
} catch (SQLException ex) {/*Error message*/return null;}
}
But actually I don't know what does getArray() returns, and I don't find any information about it.
If someone can help, I'll be thankful.
Also if getArray() doesn't work like I think it does, could you please tell me how to do what I want?
Here is the standard jdbc approach, which requires lots of boilerplate code and temporary variables, and the same thing with a more elegant add-on library, jdbi, which lets you use a much simpler fluent API:
jdbi approach:
public static List<String> jdbiEmployeeNameQuery(Handle h) {
return h.createQuery("select name from employees order by id").map(StringMapper.FIRST).list();
}
jdbc approach:
public static List<String> jdbcEmployeeNameQuery(Connection dbConnection) throws SQLException {
try (Statement s = dbConnection.createStatement()) {
try (ResultSet rs = s.executeQuery("select name from employees order by id")) {
List<String> names = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(1));
}
return names;
}
}
}
try something like this :
List list = new ArrayList();
while (resultSetObject.next()) {
list.add(resultSetObject.getString("columnName"));
}
You can convert it to String array if you want which I think is not necessary
String[] arrOfString = (String[]) list.toArray(new String[list.size()]);
I am currently learning JDBC and can successfully query and retrieve data from a MysQL database. But I would like to run this as a method and return the resultset rows from the method to the calling program.
So far I think I have made an appropriate method but am stuck returning the resultset as an object. Eclipse gives me the following error for the return type:
Object cannot be resolved to a type
Here is the method:
public object getAllPosts(int catID) throws Exception{
try{
this.catID = catID;
sql = "SELECT post_id, post_title, post_content, post_date FROM crm_posts WHERE cat_id = ? LIMIT ?";
prep = conn.prepareStatement(sql);
prep.setInt(1, catID);
prep.setInt(2, 3);
// execute statement
rs = prep.getResultSet();
} catch(Exception e){
e.printStackTrace();
}
return rs;
}
What is the return type I should use or is there a better way of doing this?
EDIT:
As stated in the comments it was a (annoying) typo. Object with a capital O.
If you're not going to return a ResultSet or Object object, then you should define your return type. You could create your own Post object for each row in the ResultSet, put those objects in a list, and return the list.
This is how you do it
public List<MyClassThatRepresentsTableInDatabase> getAllPosts(int catID) throws Exception{
try{
this.catID = catID;
sql = "SELECT post_id, post_title, post_content, post_date FROM crm_posts WHERE cat_id = ? LIMIT ?";
prep = conn.prepareStatement(sql);
prep.setInt(1, catID);
prep.setInt(2, 3);
// execute statement
rs = prep.getResultSet();
List<MyClassThatRepresentsTableInDatabase> ret=new ArrayList<>();
while(rs.hasNext()){
MyClassThatRepresentsTableInDatabase item=
new MyClassThatRepresentsTableInDatabase();
item.setId(rs.getLong("post_id");
item.setName(rs.getString("post_title");
item.setContentd("post_content");
//etc..
ret.add(item);
}
return ret;
} catch(Exception e){
e.printStackTrace();
}
return new ArrayList();
}
Excecute your query in ResultSet and loop it to get your results.
Use the following line of codes :
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
out.println(rs.getString("//Your Column name"));
}
I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.
I am trying to get all the results from multiple rows returned by the same where condition:
public static String getResult(String mycondition)
{
ResultSet rsData = sql.RunSelect("select col1 from my_table where con ='"+myCondition+"'");
if (rsData.next())
{
String result = rsData,getString("col1");
}
}
Note that there is an id column that makes these rows distinguishable.
The display in jsp page should make text fields for every row returned.
Any thoughts?
You can return a List<String> or use a char to separate the multiple strings in a single String. IMO it would be better returning a List<String>:
public static List<String> getResult(String mycondition) {
List<String> results = new ArrayList<String>();
ResultSet rsData = sql.RunSelect("select col1 from my_table where con='"
+myCondition+"'");
while (rsData.next()) {
results.add(rsData.getString("col1"));
}
return results;
}
Also, this method is prone to SQL Injection. Note that your parameters should be sent apart from the query. Probably you can improve your sql.RunSelect method to use PreparedStatement instead of Statement. This is a basic example of the code skeleton:
public ResultSet runSelect(String query, Object ... params) {
//assumes you already have your Connection
PreparedStatement pstmt = con.prepareStatement(query);
int i = 1;
for(Object param : params) {
pstmt.setObject(i++, param);
}
return pstmt.executeQuery();
}
So now you could modify your method to
public static List<String> getResult(String mycondition) {
List<String> results = new ArrayList<String>();
//using the new runSelect method
ResultSet rsData = sql.runSelect(
"select col1 from my_table where con=?", mycondition);
while (rsData.next()) {
results.add(rsData.getString("col1"));
}
return results;
}
you should use while loop instead of if loop
instead of - if (rsData.next())
use - while (rsData.next())
Although answer of #Luiggi Mendoza is best if you want security in your code
I'm using Spring-orm and HibernateTemplate to execute a native SQL query (DB is Oracle 11 for the reference), like this:
#Override
public List<Object> executeNativeQuery(final String queryStr, final Map<String, String> params) {
List<Object> results = this.template.execute(new HibernateCallback<List<Object>>() {
#Override
public List<Object> doInHibernate(Session session) throws HibernateException, SQLException {
// Get the query
Query query = session.createSQLQuery(queryStr);
// Assign parameters to the query, if any
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
query.setString(entry.getKey(), entry.getValue());
}
}
// fire the query
#SuppressWarnings("unchecked")
List<Object> res = query.list();
return res;
}
});
return results;
}
I've managed to successfully execute the query and get the results back. But I couldn't figure out a way to also get the resulting column names, and I'm starting to think that's not possible using this approach.
My problem is that I have to execute a query that comes from user input and I have no clues about parameter names.
Any ideas?
I finally found a way through it, so I post it hoping it'll be useful for others. I was doing it the wrong way, the correct way (at least for what my needs are) is to use doWork.
instad of:
session.createSQLQuery(queryStr);
I had to get the connection like this:
session.doWork(new Work() {
#Override
public void execute(Connection con) throws SQLException {
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(queryStr);
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
System.out.println("Number of Column : " + col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++) {
String col_name = md.getColumnName(i);
System.out.println(col_name);
}
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
}
}
});
Try the following to get column names in Hibernate:
public ArrayList<String> getTableDesc(String tableName){
System.out.println("getFieldNames:start"+tableName);
Object[] a;
List<Object[]> fieldNames = new ArrayList<Object[]>();
ArrayList<String> tabFieldNames = new ArrayList<String>();
Session session = getHibernateTemplate().getSessionFactory().openSession();
try{
String queryStr = "desc "+tableName;
fieldNames = (List<Object[]>) session.createSQLQuery(queryStr).list();
for(int i=0;i<fieldNames.size();i++){
a = fieldNames.get(i);
tabFieldNames.add(a[0].toString());
}
}
catch(Exception e){
System.out.println("exception "+e);
}
finally{
session.close();
}
System.out.println("getFieldNames:end"+tabFieldNames.toString());
return tabFieldNames;
}
You can use ResultTransformer class to map the query result to an entity class.
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html#d0e17313
EDIT 1:
for( int i= 0; i< ((Object[])res.get(0)).length ; i++){
//do something with data
res.get(0)[i]
}