Showing posts with label DB. Show all posts
Showing posts with label DB. Show all posts

Saturday, 9 May 2015

Finding duplicate values in a SQL table

Today I tried to find all the duplicate data in specific column in the table

below is the simple query to find it out.



Tuesday, 10 March 2015

Problem in importing excel with date/ timestamp field using oracle sql-developer

I tried to upload file in excel file to the sqldeveloper and faced problem date is null or invalid format


below is the steps how to solve it

Monday, 23 September 2013

Difference between Database and Data Source ?

A data source is simply something your program relies on to get data. A database is a kind of data source that persists data to some digitized form. Other data sources include files, services, etc — these all provide data to your programs.

Wednesday, 24 July 2013

How To insert and Retrieve image from DB #jdbc #java #MySQL

here is a few steps to insert and retrieve image files from DB.

1. Creating the Image column:


Tuesday, 9 July 2013

How to Create And start connection using #Hibernate #java

• Steps to create your first application using Hibernate:

Execute the create statement to create the table – Execute the create statement to create the table

  • Create your java project
  • Add the required jars to your project Add the required jars to your project
  • Create a java bean that’ll represent  the table
  • Create the XML mapping file which should be saved as  className.hbm.xml and located near the class
  • Create hibernate.cfg.xml to configure the Hibernate
  • Create a test class to start inserting objects in the DB.



Create a java bean that’ll represent  the table (POJO)


import  import java.util.Date java.util.Date;;
public class Employee {

private  int id;
private String name;

private Long phone;
private String address;
private Date birthdate ;

public void setName (String name) {
      this.name = name; }

public Long getPhone(){
     return phone;
}
public void   setPhone(Long phone) {
   this.phone = phone;
}
public Employee() {
}
public String getAddress() {
return address;
}
public  public int getId() {
 return id;
}
private void  setId (int id) {
   this.id = id;
}
public void  setAddress (String address) {
   this.address == address;
}
public Date  getBirthdate() {
return birthdate ;
}
public String  getName() {
   return name;
}
public void setBirthdate (Date   birthdate) {
    this.birthdate =birthdate;
}
}

and Hibernate.cfg.xml will be like


• Create hibernate.cfg.xml

this file is the main configuration file that contain

  • Driver name
  • Data base path
  • DB User Name and password
  • mapped Tables.

Example :
<hibernate--configuration>
    <session--factory name="sessionfactory">
                   <!--  driver name-->
        <property name="hibernate.connection.driver_class">
             com.mysql.jdbc.Driver
        </property>
        <!--  db path-->
         <property name ="hibernate.connection.url">
                           jdbc:mysql://localhost:3306/Hibernate
         </property>
              <!--DB username /  password-->
         <property name ="hibernate.connection.username ">root</property>
         <property name ="hibernate.connection.password"></property>
         <property name ="hibernate.dialect>
                 org.hibernate.dialect.MySQLDialect
          </property>
                   <!--table mapping-->
          <mapping resource="Employee.hbm.xml"/>
     </session factory>
 </hibernate--configuration>

How to Start the connection ?


  • Create Session Factory instance  
  • get session if exist or open new session; 
  • begin transaction with the session .   
  • do you change (persist / update the object
  • commit the change



Create a test class

import java.util.Date ;
import  org.hibernate.Session;
import org.hibernate.SessionFactory ;
import  org.hibernate.cfg.Configuration;

public class Test {

public static void main(String[] args)

{
     SessionFactory sessionFactory=  new Configuration().configure().buildSessionFactory();
     Session session = sessionFactory.openSession();
      Employee emp = new Employee();
        emp setName("name");
        emp.setPhone (new Long(1234567);
        emp.setBirthdate(new Date());
        emp.setAddress("address");
       session.beginTransaction();
       session.persist(emp);
       session.getTransaction().commit();
       System. out.println ("Insertion Done");
}
}

Good luck

Sunday, 30 June 2013

How to Set TimeStamp from a Date object and change it in #Java ? #JDBC


You can find the current Date using :

import java.sql.Timestamp;
import java.util.Date;
 
public class GetCurrentTimeStamp 
{
    public static void main( String[] args )
    {
  java.util.Date date= new java.util.Date();
  System.out.println(new Timestamp(date.getTime()));
    }
}


you can also set a special date by using below codes.but notice the trike in the month field 

Date februaryTheFirst = new Date(2013,1,1); // equals 2012-02-01
This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:
Date firstDayOf2012 = new Date(2012,0,1); // this is 2012-01-01
Exactly the same thing happens when dealing with Calendar:
Calendar.getInstance().set(2012,0,1); // 2012-01-01

If you want to change in Days ..

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

also u can do it using Date Object:

Date d = new Date();//intialize your date to any date Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 ); //Subtract n days 

Saturday, 9 February 2013

What is lazy loading in Hibernate?


Lazy loading means that all associated entities and collections aren't initialized if you load an entity object.


you have a parent and that parent has a collection of children. 

Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. 

Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, 

hibernate will load them automatically when you try to access a child. 

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.


Also . Hibernate will not actually load all children when you access the collection. 
Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. 
In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().
  • This feature is enabled by default in Hibernate.
  • This feature can be set on the level of one-to-one or one-to-many relations.



How To Set it false?

It can be disabled by setting the attribute lazy = “false” in the mapping file
<class name=“Parent" table=“Student">
     <set name="children“ lazy=“false“>
          <key column=“parent_ID"/>
           <one-to-many class=“Subject"/>
      </set>
</class>
  • By default / if the lazy attribute set to “true” and if the object is detached( when the session is closed)
    • calling Parent.getSubjects() will throw an Exception
    • If in the object is still in the persistence state ,calling the previous method will hit the DB and retrieve the list of Parent

  • If the lazy attribute set to “false” when retrieving the Parent’s data
    • it will retrieve the list of subjects as well
    • So calling the previous method will return the list of subjects whether in the persisted or detached mood.



JDBC vs ORM

What is JDBC?


JDBC stands for Java Database Connectivity, is a set of Java API for accessing the relational databases from Java program. The Java API enables the programmers to execute the SQL statements against the JDBC complaint database.

JDBC allows the programmers to quickly develop small Java applications that interact with the databases. 

To develop an application programmer has to:

  1. Develop the code to connect to the database 
  2. Write the code to execute the query. 

Once the query is successfully executed and result is retrieved from the database, programmer can read the data programmatically from the result set object. 

let's know Productive & Contrary of JDBC (Pros and Cons) 

Pros:

  • Clean and simple SQL processing
  • Good performance with large amounts of data.
  • Very good for small applications

Cons:

  • JDBC is not easily if it is used in large projects ( Large programming overhead)
  • Transactions and concurrency must be hand-coded
  • Handling the JDBC connections and properly closing the connection is also a big issue.
  • No encapsulation
  • Hard to maintain
  • Query is DBMS specific
  • Hard to implement MVC concept


Start Using JDBC

What is JDBC?

JDBC stands for Java Database Connectivity, is a set of Java API for accessing the relational databases from Java program. The Java API enables the programmers to execute the SQL statements against the JDBC complaint database.

JDBC allows the programmers to quickly develop small Java applications that interact with the databases. 

To develop an application programmer has to:

  1. Develop the code to connect to the database 
  2. Write the code to execute the query. 

Once the query is successfully executed and result is retrieved from the database, programmer can read the data programmatically from the result set object. 

How dose it Work ?
you will find the steps below sorted in steps :

  1. Load the Driver class.
  2. Create the connection using the static getConnection method
  3. Create a Statement class to execute the SQL statement
  4. Execute the SQL statement and get the results in a Resultset
  5. Iterate through the ResultSet, 

Code Example:

  1. // Change the connection string according to your db, ip, username and password
  2. String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";

  3. try {
  4.  
  5.     // 1_ Load the Driver class.
  6.     Class.forName("org.postgresql.Driver");
  7.     // If you are using any other database then load the right driver here.
  8.  
  9.     // 2_ Create the connection using the static getConnection method
  10.     Connection con = DriverManager.getConnection (connectionURL);
  11.  
  12.     //3_ Create a Statement class to execute the SQL statement
  13.     Statement stmt = con.createStatement();
  14.  
  15.     //4_ Execute the SQL statement and get the results in a Resultset
  16.     ResultSet rs = stmd.executeQuery("select * from table ");
  17.  
  18.     // 5 _Iterate through the ResultSet, displaying two values
  19.     // for each row using the getString method
  20.  
  21.     while (rs.next())
  22.         System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
  23. }
  24. catch (SQLException e) {
  25.     e.printStackTrace();
  26. }
  27. catch (Exception e) {
  28.     e.printStackTrace();
  29. }
  30. finally {
  31.     // Close the connection
  32.     con.close();
  33. }