Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Thursday, October 4

Using Bind Variables in query



//Following code helps to use bind variables in java and Oracle query

import org.hibernate.SessionFactory;

private SessionFactory sessionFactory;

public void method() {
      Session session = null;
      String  studentId = “R16”;
            try {
            session = sessionFactory.openSession();
String sql_select_query = "select name, class, age from class_table where id = :studentId";
            Query query = session.createSQLQuery(sql_select_query);
            query.setString("studentId", studentId);
                  List<Object[]> list = query.list();
      }          
 }

//Use catch or finally block with the above code
//Also use hibernate .jar file to implement above code

Append apostrophe with string or string items

This code would help in appending apostrophe with the string on both ends.
If there are comma separated items in string, each one would be appended with apostrophes.
Use: Appending apostrophe for query IN clause



public static final String appendAppsotophe(String str) {
            if(str!=null) {
                  String returnData = "";
                  String array[] = str.split(",");
                  returnData = "'" + array[0] + "'";
                  for (int i = 1; i < array.length; i++) {
                        returnData += ",'" + array[i].trim() + "'";
                  }
                  return returnData;
            } else {
                  return null;
            }
      }

Monday, October 1

Executing Query from Java



Before this you need to connect to database, refer to this post


Connection conn = null;
try{
         DbConnectionProvider dbConnectionProvider = new DbConnectionProvider();
         conn = dbConnectionProvider.connect();
         Statement stmt=conn.createStatement();
         String query = "SELECT NAME, AGE FROM DETAILS_TABLE";
                ResultSet rs = stmt.executeQuery(query);
                while (rs.next()){
                      System.out.println(rs.getString(1));
}}