Prepared statements are the ability to set up a statement once, and then execute it many times with different parameters. They are designed to replace building ad hoc query strings, and do so in a more secure and efficient manner. A typical prepared statement would look something like:
SELECT * FROM Employee WHERE emp_id = ?
The '?' is what is a called a placeholder. When you execute the above query, you would need to supply the value for it, which would replace the '?' in the query bove.
Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.
//code for PreparedStatementDemo.java
import java.sql.*;
public class PreparedStatementDemo
{
public static void main(String[] args) throws Exception
{
Connection con;
PreparedStatement ps;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Loading Drivers
con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Making Connection
ps=con.prepareStatement("SELECT * FROM Employee where emp_id=?");//this is prepare statement
//observe the '?'
ps.setInt(1,11);//we can also use setString("String"); for checking String
ResultSet rset=ps.executeQuery();//Execute the Prepared Statement
while(rset.next())//Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
ps.close();//Closeing Connection and PreparedStatement
con.close();
}
}
Monday, March 30, 2009
Java : Calling a Stored Procedure in a Database
Simple program for calling a stored procedure in a oracle database
In this example we are using both IN and OUT parameters, Simply passing two IN parameters and getting Addition as OUT parameter ie a = b + c.
//Here is complete tested code for Procedure.java
import java.sql.*;
public class Procedure
{
public static void main(String[] args) throws Exception
{
Connection con;
CallableStatement cs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Step 2: Making Connection
cs=con.prepareCall("{call AddNumbers(?,?,?)}");//Calling procedure
cs.registerOutParameter(1,Types.INTEGER);//Registering 1st parameter
// Register the type of the OUT parameter
//2nd parameter
cs.setInt(2,15);//here values can also be taken as command line argument
//3rd parameter
cs.setInt(3,20);
// Execute the stored procedure and retrieve the OUT value
cs.execute();
System.out.println(cs.getInt(1));//output as 35 ie 15+20
}
}
//end
This is How Procedure is created in oracle
create or replace procedure AddNumbers(a out number, b in number, c in number)
as
begin
a:=b+c;
end AddNumbers;
In this example we are using both IN and OUT parameters, Simply passing two IN parameters and getting Addition as OUT parameter ie a = b + c.
//Here is complete tested code for Procedure.java
import java.sql.*;
public class Procedure
{
public static void main(String[] args) throws Exception
{
Connection con;
CallableStatement cs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Step 2: Making Connection
cs=con.prepareCall("{call AddNumbers(?,?,?)}");//Calling procedure
cs.registerOutParameter(1,Types.INTEGER);//Registering 1st parameter
// Register the type of the OUT parameter
//2nd parameter
cs.setInt(2,15);//here values can also be taken as command line argument
//3rd parameter
cs.setInt(3,20);
// Execute the stored procedure and retrieve the OUT value
cs.execute();
System.out.println(cs.getInt(1));//output as 35 ie 15+20
}
}
//end
This is How Procedure is created in oracle
create or replace procedure AddNumbers(a out number, b in number, c in number)
as
begin
a:=b+c;
end AddNumbers;
Java : Java Database Connectivity (JDBC), Explained All four types with simple example
There are four types of JDBC drivers explained with simple examples using oracle database:
Type 1 : JDBC-ODBC bridge plus ODBC driver.
This driver translates JDBC method calls into ODBC function calls.
The Bridge implements Jdbc for any database for which an Odbc driver is available.
/********Code for Type1.java**********/
import java.sql.*;
public class Type1
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:odbc:madan","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Type 2 : Native-API, partly Java driver.
Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.
Note : to set path
set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes12.jar
/********Code for Type2.java**********/
import java.sql.*;
public class Type2
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:oracle:oci8:@madan","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Type 3 : JDBC-Net, pure Java driver.
Type 3 drivers are pure Java drivers that uses a proprietary network protocol to
communicate with JDBC middleware on the server.Its requests are passed through the
network to the middle-tier server. The middle-tier then translates the request to the
database. The middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Type 4 : Native-protocol, pure Java driver.
Type 4 drivers communicates directly with the database engine rather than through
middleware or a native library, they are usually the fastest JDBC drivers available.
This driver directly converts the java statements to SQL statements.
Note : to set path
set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes111.jar
/********Code for Type4.java**********/
import java.sql.*;
public class Type4
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:oracle:thin:@madan:1521:oracle9","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Type 1 : JDBC-ODBC bridge plus ODBC driver.
This driver translates JDBC method calls into ODBC function calls.
The Bridge implements Jdbc for any database for which an Odbc driver is available.
/********Code for Type1.java**********/
import java.sql.*;
public class Type1
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:odbc:madan","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Type 2 : Native-API, partly Java driver.
Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.
Note : to set path
set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes12.jar
/********Code for Type2.java**********/
import java.sql.*;
public class Type2
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:oracle:oci8:@madan","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Type 3 : JDBC-Net, pure Java driver.
Type 3 drivers are pure Java drivers that uses a proprietary network protocol to
communicate with JDBC middleware on the server.Its requests are passed through the
network to the middle-tier server. The middle-tier then translates the request to the
database. The middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Type 4 : Native-protocol, pure Java driver.
Type 4 drivers communicates directly with the database engine rather than through
middleware or a native library, they are usually the fastest JDBC drivers available.
This driver directly converts the java statements to SQL statements.
Note : to set path
set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes111.jar
/********Code for Type4.java**********/
import java.sql.*;
public class Type4
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers
con=DriverManager.getConnection("jdbc:oracle:thin:@madan:1521:oracle9","scott","tiger");//Step 2: Making Connection
stat=con.createStatement();//Step 3: Creating JDBC Statement
String query = "SELECT * FROM Employee";
ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement
while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}
Labels:
JDBC
Monday, March 16, 2009
java : Simple java program to read mails from your gmail account
Connecting GMail using POP3 connection with SSL
POP (Post Office Protocol 3)
This protocol defines a single mailbox for a single user and a standardized way for users to access mailboxes and download messages to their computer.
To run this code u need to download Java Mail API and JavaBeans Activation Framework
/*Here is the complete tested code for ReadGmailAccount.java*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;
public class ReadGmailAccount
{
public static void main(String[] args)
{
Properties props = System.getProperties();
props.put("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");
Session session = Session.getDefaultInstance(props,null);
URLName urln = new URLName("pop3","pop.gmail.com",995,null,"madan712@gmail.com","*******");//password
try
{
Store store = session.getStore(urln);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
for (int i = 0; i < message.length; i++)
{
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("Subject : " + message[i].getSubject());
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0)
{
System.out.print((char) stream.read());
}
}
folder.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}
POP (Post Office Protocol 3)
This protocol defines a single mailbox for a single user and a standardized way for users to access mailboxes and download messages to their computer.
To run this code u need to download Java Mail API and JavaBeans Activation Framework
/*Here is the complete tested code for ReadGmailAccount.java*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;
public class ReadGmailAccount
{
public static void main(String[] args)
{
Properties props = System.getProperties();
props.put("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");
Session session = Session.getDefaultInstance(props,null);
URLName urln = new URLName("pop3","pop.gmail.com",995,null,"madan712@gmail.com","*******");//password
try
{
Store store = session.getStore(urln);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
for (int i = 0; i < message.length; i++)
{
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("Subject : " + message[i].getSubject());
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0)
{
System.out.print((char) stream.read());
}
}
folder.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}
Labels:
mail
Java : Simple java program to Send Email from Gmail with attachments using JavaMail API
Java offers an API called Java Mail API from where we can send emails from java program. This article describes how we can send email (Gmail) with attachments using Java.
To send message with attachment we need to create an email with javax.mail.Multipart
object which basically will contains the email text message and then add a file to the second block, which both of them is an object of avax.mail.internet.MimeBodyPart.
In this example we also use the javax.activation.FileDataSource.
To run this code u need to download Java Mail API and JavaBeans Activation Framework
/*Here is the complete tested code for SendMailGmail.java*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;
public class SendMailGmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port","465");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.debug","false");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
try
{
Session session = Session.getDefaultInstance(props,null);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setSubject("Java Mail");
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This Mail is send through Java API");
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("TextFile.txt");//file to attach
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);
msg.setContent(multipart);
msg.setFrom(new InternetAddress("madan712@gmail.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));
msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","******");//password
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}
To send message with attachment we need to create an email with javax.mail.Multipart
object which basically will contains the email text message and then add a file to the second block, which both of them is an object of avax.mail.internet.MimeBodyPart.
In this example we also use the javax.activation.FileDataSource.
To run this code u need to download Java Mail API and JavaBeans Activation Framework
/*Here is the complete tested code for SendMailGmail.java*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import javax.activation.*;
public class SendMailGmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port","465");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.debug","false");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
try
{
Session session = Session.getDefaultInstance(props,null);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setSubject("Java Mail");
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This Mail is send through Java API");
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("TextFile.txt");//file to attach
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);
msg.setContent(multipart);
msg.setFrom(new InternetAddress("madan712@gmail.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));
msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","******");//password
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}
Subscribe to:
Posts (Atom)