JDBC Examples
Program of TYpe-1 Simple Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcDemo
{
public static Connection getConnection() throws
ClassNotFoundException, SQLException
{
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mydsn");
return con;
}
public static void selectData() throws ClassNotFoundException,
SQLException
{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("select name,age from user");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("name = "+rs.getString("name")+
" age = "+rs.getString("age"));
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
selectData();
}
}
Output
name = abc age = 18 name = xyz age = 20
Program of Type-1 CRUD Example
Type-1 CRUD
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcDemo
{
public static Connection getConnection() throws
ClassNotFoundException, SQLException
{
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mydsn");
return con;
}
public static void insertData() throws
ClassNotFoundException, SQLException
{
System.out.println("enter the name you want to insert = ");
String name=new Scanner(System.in).nextLine();
System.out.println("enter the age you want to insert = ");
String age=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("insert
into user(name,age) values(?,?)");
ps.setString(1, name);
ps.setString(2,age);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record added");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void selectData() throws
ClassNotFoundException, SQLException
{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("select name,age from user");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("name = "+rs.getString("name")+
" age = "+rs.getString("age"));
}
if(rs!=null)
{
rs.close();
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void updateData() throws
ClassNotFoundException, SQLException
{
System.out.print("enter old name = ");
String oldName=new Scanner(System.in).nextLine();
System.out.print("enter new name = ");
String newName=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("update user set name=? where name=?");
ps.setString(1, newName);
ps.setString(2,oldName);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record updated");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void deleteData() throws
ClassNotFoundException, SQLException
{
System.out.print("enter name to delete = ");
String name=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("delete from user where name = ");
ps.setString(1, name);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record deleted");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
while(true)
{
System.out.print("1- insert data\n2- read data\n3-
update data\n4- delete data\n5- exit\nEnter your choice =");
int choice=new Scanner(System.in).nextInt();
if(choice==1)
{
insertData();
}
if(choice==2)
{
selectData();
}
if(choice==3)
{
updateData();
}
if(choice==4)
{
deleteData();
}
if(choice==5)
{
System.exit(0);
}
else
{
System.out.println("wrong choice");
}
}
}
}
Output
Enter your choice =1
enter the name you want to insert =
abc
enter the age you want to insert =
21
1 record added
----
Enter your choice =2
name = abc age = 21
-----
Enter your choice =3
enter old name = abc
enter new name = xyz
1 record updated
------
Enter your choice =4
enter name to delete = xyz
1 record deleted
------
Enter your choice =5
Program of Type-4 Simple Example
Type-4 Simple Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcDemo
{
public static Connection getConnection() throws
ClassNotFoundException, SQLException
{
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/myDb","root","root");
return con;
}
public static void selectData() throws
ClassNotFoundException, SQLException
{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("select name,age from user");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("name = "+rs.getString("name")+
" age = "+rs.getString("age"));
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
if(rs!=null)
{
rs.close();
}
}
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
selectData();
}
}
Output
name = xyz age = 20
Example of Type-4 CRUD Example
Type-4 CRUD
T.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcDemo
{
public static Connection getConnection() throws
ClassNotFoundException, SQLException
{
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/trial","root","root");
return con;
}
public static void insertData() throws
ClassNotFoundException, SQLException
{
System.out.println("enter the name you want to insert = ");
String name=new Scanner(System.in).nextLine();
System.out.println("enter the age you want to insert = ");
String age=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("insert into user
(name,age) values(?,?)");
ps.setString(1, name);
ps.setString(2,age);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record added");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void selectData() throws
ClassNotFoundException, SQLException
{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("select name,age from user");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("name = "+rs.getString("name")+
" age = "+rs.getString("age"));
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
if(rs!=null)
{
rs.close();
}
}
public static void updateData() throws
ClassNotFoundException, SQLException
{
System.out.print("enter old name = ");
String oldName=new Scanner(System.in).nextLine();
System.out.print("enter new name = ");
String newName=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("update user set name=? where name=?");
ps.setString(1, newName);
ps.setString(2,oldName);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record updated");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void deleteData() throws
ClassNotFoundException, SQLException
{
System.out.print("enter name to delete = ");
String name=new Scanner(System.in).nextLine();
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement
("delete from user where name = ?");
ps.setString(1, name);
int count=ps.executeUpdate();
if(count>0)
{
System.out.println(count+" record deleted");
}
if(ps!=null)
{
ps.close();
}
if(con!=null){
con.close();
}
}
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
while(true)
{
System.out.print("1- insert data\n2- read data\n3- update data\n4-
delete data\n5- exit\nEnter your choice =");
int choice=new Scanner(System.in).nextInt();
if(choice==1)
{
insertData();
}
if(choice==2)
{
selectData();
}
if(choice==3)
{
updateData();
}
if(choice==4)
{
deleteData();
}
if(choice==5)
{
System.exit(0);
}
else
{
System.out.println("wrong choice");
}
}
}
}
Output
Enter your choice =1 enter the name you want to insert = ABC enter the age you want to insert = 30 1 record added ------- Enter your choice =2 name = ABC age = 30 ------ Enter your choice =3 enter old name = ABC enter new name = XYZ 1 record updated ------ Enter your choice =4 enter name to delete = XYZ 1 record deleted --------- Enter your choice =5
Transaction Management Example
Transaction Management Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TransManagement
{
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
PreparedStatement pstmt = null;
PreparedStatement pstmtInsert = null;
ResultSet rs = null;
boolean r = false;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root","root");
con.setAutoCommit(false);
if(con == null)
{
System.out.println("Error in MySQL Connection ....");
System.exit(0);
}
pstmtInsert = con.prepareStatement("insert into
emp(empno,name)values(?,?)");
pstmtInsert.setInt(1, 1004);
pstmtInsert.setString(2, "ABCD32323");
pstmtInsert.executeUpdate();
if(r)
{
con.commit();
System.out.println("Record Added");
}
else
{
con.rollback();
System.out.println("Record RollBack");
}
pstmtInsert.close();
/*pstmt = con.prepareStatement("select empno ,
name from emp ");
rs = pstmt.executeQuery();
while(rs.next()){
System.out.println("Empno "+rs.getInt("empno")+
" Name "+rs.getString("name"));
}*/
/*rs.close();*/
/*pstmt.close();*/
con.close();
}
}
Output
Batch Update Example
Batch Update Example
package project1;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class BatchUpadate
{
public BatchUpadate()
{}
private Connection getConnection() throws
ClassNotFoundException, SQLException
{
Connection con=null;
Class.forName("com.mysql.jdbc.Driver");//Driver name of mysql
con=DriverManager.getConnection("jdbc:mysql://localhost/User_DSN",
"root","harry");//connection path ,user and password.
if(con!=null)
{
System.out.println("connection");//connection check
}
else
{
System.out.println("no connection..");
}
return con;
}
boolean insertTable() throws ClassNotFoundException, SQLException
{
boolean isTrue=false;
PreparedStatement psmt=null;
Connection con=null;
String insertTableSQL = "INSERT INTO user"
+ "(userid, pwd, createdby , created_date) VALUES"
+ "(?,?,?,?)";// query for insert table
con = getConnection();
psmt = (PreparedStatement)con.prepareStatement(insertTableSQL);
con.setAutoCommit(false);
psmt.setString(1,"techknow");
psmt.setString(2, "heights");
psmt.setString(3, "system");
psmt.setTimestamp(4, getCurrentTimeStamp());
psmt.addBatch();//add batch 1 here
psmt.setString(1,"techknow");
psmt.setString(2, "tkhts");
psmt.setString(3, "system");
psmt.setTimestamp(4, getCurrentTimeStamp());
psmt.addBatch();// add batch 2 here
psmt.setString(1,"techknow");
psmt.setString(2, "systemdb");
psmt.setString(3, "system");
psmt.setTimestamp(4, getCurrentTimeStamp());
psmt.addBatch();//add batch 3 here
psmt.setString(1,"techknow");
psmt.setString(2, "tkh-heights");
psmt.setString(3, "system");
psmt.setTimestamp(4, getCurrentTimeStamp());
psmt.addBatch();//add batch 4 here
psmt.setString(1,"techknow");
psmt.setString(2, "tkh");
psmt.setString(3, "system");
psmt.setTimestamp(5, getCurrentTimeStamp());
psmt.addBatch(); // add batch 5 here
psmt.executeBatch();
//excute the all batch
con.commit();// commit the database
System.out.println("Record is inserted into DBUSER table!");
return isTrue;// return the result
}
private static java.sql.Timestamp getCurrentTimeStamp()
{
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime()); //method to
change the java.util.date into java.sql.lang
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException
{
BatchUpadate batchUpadate = new BatchUpadate();
// create the BatchUpdate class object
batchUpadate.insertTable();
}
}
Output
T class default cons Name disp Name output Name add Name show
ResultSet MetaData Example
ResultSet MetaData Example
import java.sql.*;
import java.io.*;
public class ResultSetMetaDataDemo1
{
Connection con;
public ResultSetMetaDataDemo1()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql;
//localhost/rst?user=root&password=sonu");
}
catch(Exception e)
{
System.out.println("Error in Connection"+e);
}
}
public void displyRecords(String tableName)
{
String columnHeading="";
try
{
Statement stmt=con.createStatement();
ResultSet res=stmt.executeQuery("select* from "+tableName.trim());
if(res.next())
{
ResultSetMetaData rsmd=res.getMetaData();
int colomntype=rsmd.getColomnDisplaySize(3);
System.out.println(colomntype);
int columnCount=rsmd.getColumnCount();
for(int i=1;i<=columnCount;i++)
{
columnHeading=columnHeading+"\t"+rsmd.getColumnName(i);
}
System.out.println(columnHeading);
while(res.next())
{
for(int i=1;i<=columnCount;i++)
{
System.out.println("\t"+res.getString(i));
}
System.out.println("\n");
}
}
else
System.out.println("There is no records in table");
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
ResultSetMetaDataDemo1 obj=new ResultSetMetaDataDemo1();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String choice="";
try
{
do
{
System.out.println("Enter table name to display
records using ResultSetMetaData interface");
String name=br.readLine();
obj.displyRecords(name);
System.out.println("Do you want to continue(yes)");
choice=br.readLine();
}
while(choice.trim().equals("yes"));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output
Example of DataBaseMetaData
Example of DataBaseMetaData
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import com.mysql.jdbc.Driver;
public class DataBaseMetaData
{
static
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static Connection getConnection()
{
Connection connection=null;
try
{
connection=DriverManager.getConnection
("jdbc:mysql://localhost:3306/demo2","root","root");
}
catch(Exception e)
{
e.printStackTrace();
}
return connection;
}
public static void main(String args[])
{
Connectionn con=getConnection();
try
{
DataBaseMetaData dbmd=con.getMetaData();
System.out.println("dbmd:driver version =
"+dbmd.getDriverVersion());
System.out.println("dbmd:driver name =
"+dbmd.getDriverName());
System.out.println("db name =
"+dbmd.getDatabaseProductName());
System.out.println("db version =
"+dbmd.getDatabaseProductVersion());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output
Example of Rowset
Example of Rowset
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl;
public class JDBCRowSetExample
{
public static void main(String[] args) throws Exception
{
Connection connection = getMySqlConnection();
System.out.println("Connection Done");
Statement statement = connection.createStatement();
JdbcRowSet jdbcRowSet;
jdbcRowSet = new JdbcRowSetImpl(connection);
jdbcRowSet.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
String queryString = "SELECT * FROM student";
jdbcRowSet.setCommand(queryString);
jdbcRowSet.execute();
jdbcRowSet.addRowSetListener(new ExampleListener());
while (jdbcRowSet.next())
{
// Generating cursor Moved event
System.out.println("Roll No- " + jdbcRowSet.getString(1));
System.out.println("name- " + jdbcRowSet.getString(2));
}
connection.close();
}
// My Sql connection method
public static Connection getMySqlConnection() throws Exception
{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "root";
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
return connection;
}
}
class ExampleListener implements RowSetListener
{
@Override
public void cursorMoved(RowSetEvent event)
{
// TODO Auto-generated method stub
System.out.println("Cursor Moved Listener");
System.out.println(event.toString());
}
@Override
public void rowChanged(RowSetEvent event)
{
// TODO Auto-generated method stub
System.out.println("Cursor Changed Listener");
System.out.println(event.toString());
}
@Override
public void rowSetChanged(RowSetEvent event)
{
// TODO Auto-generated method stub
System.out.println("RowSet changed Listener");
System.out.println(event.toString());
}
}
Output



