At Jaipur on Tonk Road.. Funny

How to Insert or Get Back Image File with DataBase in using Java Programs

import java.sql.*;
import java.util.*;
import java.io.*;
public class InsertBlob
{
public static void main(String ar[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","me");
String qry = "insert into imagee values(?,?,?)";
PreparedStatement ps=con.prepareStatement(qry);
ps.setString(1,"Chetan");
ps.setString(2,"Chauhan");
File f = new File("Butterfly.jpg");
FileInputStream fis = new FileInputStream(f);
System.out.println((int)f.length());
ps.setBinaryStream(3,fis,(int)f.length());
int i = ps.executeUpdate();
System.out.println(i+ " Record inserted successfully");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

...........................
To Get Image From DataBase

<%@page import="java.sql.*,java.io.*"%>
<% InputStream sImage; response.setContentType("image/jpeg"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","me"); Statement stmt = con.createStatement(); String qry="select * from imagee"; ResultSet rs=stmt.executeQuery(qry); if(rs.next()) { byte[] bytearray = new byte[1048576]; response.setContentLength(bytearray.length); int size=0; sImage = rs.getBinaryStream(3); //response.reset(); while((size=sImage.read(bytearray))!= -1) { response.getOutputStream().write(bytearray,0,size); } } } catch(Exception e) { System.out.println(e); } %>

FrameWork Program Collection in Java

DemoAL.java


import java.util.ArrayList;
import java.util.Iterator;


public class DemoAL {


public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("JAVA");
al.add("PHP");
al.add("ORACLE");
al.add("ASP.NET");


System.out.println(al);




System.out.println("-------------------------------------");
/*for(String s:al)
{
System.out.println(s);
}*/


Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());


}
}


}
-----------------------


DemoALDataBase




import java.util.ArrayList;
import java.sql.*;
class DemoDB
{
String user,pass;
int sno;
DemoDB(String user,String pass,int sno)
{
this.user=user;
this.pass=pass;
this.sno=sno;
}


}
public class DemoALDataBase {




public ArrayList showResultAL()
{
ArrayList al=new ArrayList();


try
{
Class.forName("com.mysql.jdbc.Driver"); //type 4 driver
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","rat");//connection
System.out.println("Connection successful:"+con);
Statement stmt=con.createStatement();//creating statement for the further
ResultSet res=stmt.executeQuery("select * from login");
while(res.next())
{
String u=res.getString(1);
String p=res.getString(2);
int sno=res.getInt(3);


al.add(new DemoDB(u,p,sno));
}
}
catch(Exception e )
{
}


System.out.println("size is :"+al.size());








return al;
}


public static void main(String args[])
{
DemoALDataBase ob=new DemoALDataBase();
ArrayList al=ob.showResultAL();


DemoDB obj=al.get(2);
System.out.println(obj.user+","+obj.pass+","+obj.sno);


/* for(DemoDB obj:al)
{
System.out.println(obj.user+","+obj.pass+","+obj.sno);
}*/
}


}
-----------------------------
DemoHashMap.java


import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
public class DemoHashMap {
public static void main(String[] args) {
//create HashMap object
HashMap hMap = new HashMap();
//add key value pairs to HashMap
hMap.put("1","ram");
hMap.put("2","shyam");
hMap.put("3","mohan");
/*
get Collection of values contained in HashMap using
Collection values() method of HashMap class
*/
Collection c = hMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through HashMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
}
}
----------------------------
DemoHashMap1.java




import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


public class DemoHashMap1 {


public static void main(String[] args) {


//create HashMap object
HashMap hMap = new HashMap();


//add key value pairs to HashMap
hMap.put("1","java");
hMap.put("2","php");
hMap.put("3","oracle");


Set s=hMap.keySet();
System.out.println("size is :"+s.size());


String arr[]=new String[s.size()];
Iterator itr=s.iterator();
for(int i=0;i
{
arr[i]=itr.next();
System.out.println(arr[i]+":"+hMap.get(arr[i]));
}


// System.out.println(hMap.get("3"));
}
}

A Simple Struts Program to Verify User Name or Password

DemoAction.java
package com.rat.action;

import java.sql.*;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class DemoAction extends ActionSupport implements Preparable,ModelDriven
{
          DemoBean obj;
          Connection con;
          Statement stmt;
          PreparedStatement ps;
         
         
         
          public void prepare() throws Exception
          {
                   obj=new DemoBean();
                   try
                   {
    Class.forName("com.mysql.jdbc.Driver");  //type 4 driver
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","rat");//connection
   System.out.println("Connection successful:"+con);
   stmt=con.createStatement();
                   }
                   catch(Exception e)
                   {
                             e.printStackTrace();
                   }
          }
_________________________________________________

DemoBean.java
package com.rat.action;

public class DemoBean 
{
  private String uname="",pass="";
  public void setUname(String uname)
  {
            this.uname=uname;
  }
  public void setPass(String pass)
  {
            this.pass=pass;
  }
  public String getUname()
  {
            return uname;
  }
  public String getPass()
  {
            return pass;
  }

 }
_________________________________________________

ViewAllAction.java

package com.rat.action;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class ViewAllAction extends ActionSupport  implements Preparable,ApplicationAware
{
          Connection con;
          Statement stmt;
          DemoBean obj;
          Map application;
          public void setApplication(Map application)
          {
                   this.application=application;
          }
          public void prepare()
          {
                  
                   try
                    {
       Class.forName("com.mysql.jdbc.Driver");  //type 4 driver
       con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","rat");//connection 
        System.out.println("Connection successful:"+con);
       stmt=con.createStatement();
                   }
                   catch(Exception e)
                   {
                             e.printStackTrace();
                   }
          }

Retrieving blob values from database in string format Java Program

import java.sql.*;

public class DemoBlob
{
public static void main(String args[])throws Exception
{

Class.forName("com.mysql.jdbc.Driver");  //type 4 driver
 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","rat");//connection
System.out.println("Connection successful:"+con);
 PreparedStatement ps=con.prepareStatement("select * from login");
 ResultSet res=ps.executeQuery();
 res.next();

        Blob b= res.getBlob(1);
        long len=b.length();
       
        byte value[]=b.getBytes(1, (int)(len));
        String str=new String(value);
        System.out.println(str);
}
}

A Simple Java Program to Insert Value in DataBase

import java.util.Date;
import java.sql.*;

public class DemoDate
{
public static void main(String args[])throws Exception
{
Date d=new Date();
long l=d.getTime();
System.out.println(l);
java.sql.Date obj=new java.sql.Date(l);
Class.forName("com.mysql.jdbc.Driver");  //type 4 driver
 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","rat");//connection
System.out.println("Connection successful:"+con);
 PreparedStatement ps=con.prepareStatement("insert into demo values(?)");
 ps.setDate(1, obj);
 ps.executeUpdate();
 System.out.println("operation successful");


 ps=con.prepareStatement("select * from demo");
 ResultSet res=ps.executeQuery();
 res.next();
 d=res.getDate(1);
 System.out.println(d);
}
}

Create A Media Player in Java Or Play Files

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.media.*;

public class MediaPlayerDemo extends JFrame
{
private Player player;
private File file;

public MediaPlayerDemo()
{
super( "Java Media Player" );

JButton openFile = new JButton( "Open file (Browse) to play" );
openFile.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
openFile();
createPlayer();
}
});
getContentPane().add( openFile, BorderLayout.NORTH );

setSize( 100, 200 );
show();
}

private void openFile()
{
JFileChooser fileChooser = new JFileChooser();

fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );

if ( result == JFileChooser.CANCEL_OPTION )
file = null;
else
file = fileChooser.getSelectedFile();
}

private void createPlayer()
{
if ( file == null )
return;

removePreviousPlayer();

try
{
player = Manager.createPlayer( file.toURL() );
player.addControllerListener( new EventHandler() );
player.start();
}
catch ( Exception e )
{
JOptionPane.showMessageDialog( this, "Invalid file or location", "Error loading file",
JOptionPane.ERROR_MESSAGE );
}
}

private void removePreviousPlayer()
{
if ( player == null )
return;

player.close();

Component visual = player.getVisualComponent();
Component control = player.getControlPanelComponent();

Container c = getContentPane();

if ( visual != null )
c.remove( visual );

if ( control != null )
c.remove( control );
}

public static void main(String args[])
{
MediaPlayerDemo app = new MediaPlayerDemo();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit(0);
}
}
}

private class EventHandler implements ControllerListener
{
public void controllerUpdate( ControllerEvent e )
{
if ( e instanceof RealizeCompleteEvent )
{
Container c = getContentPane();

Component visualComponent = player.getVisualComponent();

if ( visualComponent != null )
c.add( visualComponent, BorderLayout.CENTER );

Component controlsComponent = player.getControlPanelComponent();

if ( controlsComponent != null )
c.add( controlsComponent, BorderLayout.SOUTH );

c.doLayout();
}
}
}
}

A simple Audio File Load and Play Java Program

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoadAudioAndPlay extends JApplet
{
private AudioClip sound1, sound2, currentSound;
private JButton playSound, loopSound, stopSound;
private JComboBox chooseSound;

public void init()
{
Container c = getContentPane();
c.setLayout( new FlowLayout() );

String choices[] = { "Welcome", "Hi" };
chooseSound = new JComboBox( choices );
chooseSound.addItemListener( new ItemListener()
{
public void itemStateChanged( ItemEvent e )
{
currentSound.stop();

currentSound = chooseSound.getSelectedIndex() == 0 ? sound1 : sound2;
}
});
c.add( chooseSound );

ButtonHandler handler = new ButtonHandler();
playSound = new JButton( "Play" );
playSound.addActionListener( handler );
c.add( playSound );
loopSound = new JButton( "Loop" );
loopSound.addActionListener( handler );
c.add( loopSound );
stopSound = new JButton( "Stop" );
stopSound.addActionListener( handler );
c.add( stopSound );

sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );
sound2 = getAudioClip( getDocumentBase(), "hi.au" );
currentSound = sound1;
}

public void stop()
{
currentSound.stop();
}

private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent e )
{
if ( e.getSource() == playSound )
currentSound.play();
else if ( e.getSource() == loopSound )
currentSound.loop();
else if ( e.getSource() == stopSound )
currentSound.stop();
}
}
}