0% found this document useful (0 votes)
14 views

JDBC Practise Programs

It is a SQL document You can practice it its a basic to SQL. I recommended to try this at once. Thank you !

Uploaded by

vaishuravi1003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JDBC Practise Programs

It is a SQL document You can practice it its a basic to SQL. I recommended to try this at once. Thank you !

Uploaded by

vaishuravi1003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

JDBC

Syllabus :

1. Introduction to JDBC: 6. Transaction Management:


Understanding the role of JDBC in Java Understanding the concept of transactions in
database programming a database
Overview of the JDBC architecture and its Enabling and disabling auto-commit mode
components Committing and rolling back transactions
Different types of JDBC drivers and their Handling transaction-related exceptions and
characteristics errors

2. Establishing Database Connections: 7. Batch Processing:


Loading the JDBC driver class Performing batch updates to improve
Establishing a connection to a database performance
using DriverManager Creating and executing batch statements
Managing connection parameters (URL, Handling batch execution errors and
username, password) exceptions
Handling exceptions related to connection
establishment 8. Connection Pooling:
Introduction to connection pooling and its
3. Executing SQL Statements: benefits
Creating Statement and PreparedStatement Configuring a connection pool using
objects frameworks like Apache Commons DBCP or
Executing SQL queries (SELECT statements) HikariCP
and retrieving result sets Managing and reusing connections from a
Executing SQL updates (INSERT, UPDATE, connection pool
DELETE statements) Handling Database Metadata:
Handling exceptions related to SQL execution
9. Retrieving database metadata using
4. Retrieving and Processing Result Sets: DatabaseMetaData
Navigating through result sets using the Extracting information about database
ResultSet object schemas, tables, and columns
Retrieving data from result sets (by column Accessing and interpreting database-specific
index or name) information
Handling different data types (numeric, string,
date, etc.) 10. Advanced JDBC Concepts:
Performing operations on result sets (sorting, Handling large objects (BLOBs and CLOBs)
filtering, aggregation) Working with stored procedures and callable
statements
5. Parameterized Queries: Using scrollable and updatable result sets
Using PreparedStatement for parameterized Implementing database cursors and result set
queries pagination
Setting parameter values dynamically
Preventing SQL injection attacks with 11 Best Practices and Performance
prepared statements Optimization:
Writing efficient and optimized JDBC code
Using appropriate fetch sizes and result set
types
Properly closing resources (connections,
statements, result sets)
Employing connection pooling and caching
techniques

****************************************************************************************************
Programs

Program for prepared statement with a LIMIT of 10

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {

public static void main(String[] args) {

//String query = "SELECT first_name, last_name FROM customers LIMIT ?";

try {
//Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");
//Statement stmt=con.createStatement();
String query = "SELECT first_name, last_name FROM customers LIMIT
?";
PreparedStatement preparedStatement = con.prepareStatement(query);
//int limit=10;
preparedStatement.setInt(1, 10);
System.out.println("getting the data");

ResultSet rs=preparedStatement.executeQuery();
while(rs.next()) {
String name=rs.getString("first_name");
String lname=rs.getString("last_name");

//printing name
System.out.print("Name : " + name);
System.out.print(" Last Name : " + lname);
System.out.println(" |");
}
// Close the resources
rs.close();
//stmt.close();
con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}}}
Scrollable ResultSet with next(), last(), previous(), at a absolute position 3 with a LIMIT
of 10

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {

public static void main(String[] args) {

//String query = "SELECT first_name, last_name FROM customers LIMIT ?";

try {
//Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");
//Statement stmt=con.createStatement();
String query = "SELECT first_name, last_name FROM customers LIMIT
?";
PreparedStatement preparedStatement = con.prepareStatement(query,
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//int limit=10;
preparedStatement.setInt(1, 10);
System.out.println("getting the data");

ResultSet rs=preparedStatement.executeQuery();

System.out.println("******************ResultSet Move
Forward*********************");
while(rs.next()) {
String name=rs.getString("first_name");
String lname=rs.getString("last_name");

//printing name
System.out.print("Name : " + name);
System.out.print(" Last Name : " + lname);
System.out.println(" |");
}

System.out.println("******************ResultSet At last*********************");

//rs.last();

System.out.println("******************ResultSet Move
Backward*********************");

while(rs.previous()) {
String name=rs.getString("first_name");
String lname=rs.getString("last_name");

//printing name
System.out.print("Name : " + name);
System.out.print(" Last Name : " + lname);
System.out.println(" |");
}

System.out.println("******************ResultSet At Position
3*********************");

rs.absolute(3);
String name=rs.getString("first_name");
String lname=rs.getString("last_name");

//printing name
System.out.print("Name : " + name);
System.out.print(" Last Name : " + lname);
System.out.println(" |");
// Close the resources
rs.close();
//stmt.close();
con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}

O/P-
connecting to database
getting the data
******************ResultSet Move Forward*********************
Name : Babara Last Name : MacCaffrey |
Name : Ines Last Name : Brushfield |
Name : Freddi Last Name : Boagey |
Name : Ambur Last Name : Roseburgh |
Name : Clemmie Last Name : Betchley |
Name : Elka Last Name : Twiddell |
Name : Ilene Last Name : Dowson |
Name : Thacher Last Name : Naseby |
Name : Romola Last Name : Rumgay |
Name : Levy Last Name : Mynett |
******************ResultSet At last*********************
******************ResultSet Move Backward*********************
Name : Levy Last Name : Mynett |
Name : Romola Last Name : Rumgay |
Name : Thacher Last Name : Naseby |
Name : Ilene Last Name : Dowson |
Name : Elka Last Name : Twiddell |
Name : Clemmie Last Name : Betchley |
Name : Ambur Last Name : Roseburgh |
Name : Freddi Last Name : Boagey |
Name : Ines Last Name : Brushfield |
Name : Babara Last Name : MacCaffrey |
******************ResultSet At Position 3*********************
Name : Freddi Last Name : Boagey |

Program to Insert the values in the My sql database

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {


public static void main(String[] args) {

//String query = "SELECT first_name, last_name FROM customers LIMIT ?";

try {
//Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");
//Statement stmt=con.createStatement();
String query = "SELECT * FROM customers LIMIT ?";
PreparedStatement preparedStatement = con.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//int limit=10;
preparedStatement.setInt(1, 10);
System.out.println("getting the data");

ResultSet rs=preparedStatement.executeQuery();

rs.moveToInsertRow();
rs.updateString("first_name", "pinku");
rs.updateString("last_name", "Gaykwad");
rs.updateInt("phone", 777777777);
rs.updateString("birth_date", "2023-04-05");
rs.updateString("address", "buldhana");
rs.updateString("city", "buldhan");
rs.updateString("state", "dd");
rs.updateInt("points", 1000);
rs.insertRow();

// Close the resources


rs.close();
//stmt.close();
con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}

}
private static void moveToInsertRow() {
// TODO Auto-generated method stub
}}
Inserted into database :
16 pinku Gaykwad 2023-04-05 77777777 buldhan buldhan dd 1000
7 a

Program to update a phone number and points by using absolute method with the help of
preparedStatement

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {

public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query = "SELECT * FROM customers ";


PreparedStatement preparedStatement = con.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

System.out.println("getting the data");

ResultSet rs=preparedStatement.executeQuery();

rs.absolute(14);
rs.updateInt("points", 10000);
rs.updateString("phone", "11111111111");
rs.updateRow();
System.out.println("Phone number & points updated successfully.");
// Close the resources
rs.close();
//stmt.close();
con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}

private static void moveToInsertRow() {


// TODO Auto-generated method stub

O/P-

14 Aru Pawa 11111111 june Akola MH 10000


r 111 gao

Inserted a row in a data base with each value

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {


public static void main(String[] args) {
try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query = "INSERT INTO products VALUES(?,?,?,?)";


PreparedStatement preparedStatement = con.prepareStatement(query);

System.out.println("Inserting data");
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Wire");
preparedStatement.setInt(3, 50);
preparedStatement.setDouble(4, 6.6);
int NumberOfRowInserted=preparedStatement.executeUpdate();
System.out.println("Number of inseted row : "+ NumberOfRowInserted);

//stmt.close();
con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}

private static void moveToInsertRow() {


// TODO Auto-generated method stub

}
O/P-
connecting to database
Inserting data
Number of inseted row : 1

Updating a phone number in a database where customer id is 5

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {

public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query = "UPDATE customers SET phone=? WHERE


customer_id=5";
PreparedStatement preparedStatement = con.prepareStatement(query);

System.out.println("Updating data");
preparedStatement.setString(1, "9822200930");

int NumberOfRowInserted=preparedStatement.executeUpdate();
System.out.println("Number of inseted row : "+ NumberOfRowInserted);

con.close();
preparedStatement.close();
}catch (SQLException e) {
e.printStackTrace();
}
}

private static void moveToInsertRow() {


// TODO Auto-generated method stub

}
O/P-
connecting to database
Updating data
Number of inseted row : 1

Program to Read Data from the database :

package JdbcConnectionDemo;
import java.io.PrintStream;
import java.sql.*;

public class JdbcDemo {

public static void main(String[] args) {

try {
System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query="SELECT * FROM products";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");

ResultSet rs=ps.executeQuery();
while(rs.next()) {
int Pid=rs.getInt(1);
String name=rs.getString(2);
int qtyStock=rs.getInt(3);
double price=rs.getDouble(4);

//printing the result


System.out.println("Product ID : "+ Pid);
System.out.println("Product Name : "+ name);
System.out.println("Qty In stock : "+ qtyStock);
System.out.println("Price : "+ price);
System.out.println("*****************************");
}
rs.close();
con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}}

private static void moveToInsertRow() {


// TODO Auto-generated method stub

Deleted the Row in the database


package JdbcConnectionDemo;
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store",
"root", "123123azAZ@");

String query="DELETE FROM customers WHERE


customer_id=?";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1, 16);

System.out.println("Executing query");

int DeleteRow=ps.executeUpdate();

System.out.println("Deleted Row : "+ DeleteRow);

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
Program for LIKE clause demo, getting dat from user and like single char and obtaining data
which matches user input

package JdbcConnectionDemo;
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 void main(String[] args) {

JdbcDemo j=new JdbcDemo();


Scanner sc=new Scanner(System.in);
System.out.println("Enter the Name : ");
while(sc.hasNext()) {
String pname =sc.nextLine();
if(pname.equalsIgnoreCase("Exit")) {
break;
}
j.GetProductInfo(pname);
System.out.println("\nEnter the Name : ");
}
}
private void GetProductInfo(String pname) {
try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query="SELECT * FROM products WHERE name LIKE


'"+pname+"%' ";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");
ResultSet rs=ps.executeQuery();
while(rs.next()) {
int Pid=rs.getInt(1);
String name=rs.getString(2);
int qtyStock=rs.getInt(3);
double price=rs.getDouble(4);

//printing the result


System.out.println("Product ID : "+ Pid);
System.out.println("Product Name : "+ name);
System.out.println("Qty In stock : "+ qtyStock);
System.out.println("Price : "+ price);
System.out.println("*****************************");
}
rs.close();

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}

O/P
Enter the Name :L
connecting to database
creating connection
Executing query
Product ID : 3
Product Name : Lettuce - Romaine, Heart
Qty In stock : 38
Price : 3.35
*****************************
Product ID : 9
Product Name : Longan
Qty In stock : 67
Price : 2.26
*****************************
Enter the Name : a
connecting to database
creating connection
Executing query
Enter the Name : B
connecting to database
creating connection
Executing query
Product ID : 4
Product Name : Brocolinni - Gaylan, Chinese
Qty In stock : 90
Price : 4.53
*****************************
Product ID : 10
Product Name : Broom - Push
Qty In stock : 6
Price : 1.09
*****************************
Enter the Name : S
connecting to database
creating connection
Executing query
Product ID : 5
Product Name : Sauce - Ranch Dressing
Qty In stock : 94
Price : 1.63
*****************************
Product ID : 7
Product Name : Sweet Pea Sprouts
Qty In stock : 98
Price : 3.29
*****************************
Program for sorting the data by Ascending & order and descending order

package JdbcConnectionDemo;
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 void main(String[] args) {

JdbcDemo j=new JdbcDemo();


Scanner sc=new Scanner(System.in);
System.out.println("Enter the Accesding or Descending : ");
while(sc.hasNext()) {
String orderBy =sc.nextLine();
if(orderBy.equalsIgnoreCase("Exit")) {
break;
}
j.GetProductInfo(orderBy);
System.out.println("\nEnter the Accesding or Descending : ");
}
}
private void GetProductInfo(String orderBy) {
try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query;
if(orderBy.equalsIgnoreCase("Ascending")) {
query="SELECT * FROM products ORDER BY name ASC";
}
else {
query="SELECT * FROM products ORDER BY name
DESC";
}

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");

ResultSet rs=ps.executeQuery();
while(rs.next()) {
int Pid=rs.getInt(1);
String name=rs.getString(2);
int qtyStock=rs.getInt(3);
double price=rs.getDouble(4);

//printing the result


System.out.println("Product ID : "+ Pid);
System.out.println("Product Name : "+ name);
System.out.println("Qty In stock : "+ qtyStock);
System.out.println("Price : "+ price);
System.out.println("*****************************");
}
rs.close();

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();}}}
O/p-
Enter the Accesding or Descending Enter the Accesding or Descending
ascending descending
connecting to database connecting to database
creating connection creating connection
Executing query Executing query
Product ID : 4 Product ID : 11
Product Name : Brocolinni - Gaylan, Chinese Product Name : Wire
Qty In stock : 90 Qty In stock : 50
Price : 4.53 Price : 6.6
***************************** *****************************
Product ID : 10 Product ID : 7
Product Name : Broom - Push Product Name : Sweet Pea Sprouts
Qty In stock : 6 Qty In stock : 98
Price : 1.09 Price : 3.29
***************************** *****************************
Product ID : 1 Product ID : 5
Product Name : Foam Dinner Plate Product Name : Sauce - Ranch Dressing
Qty In stock : 70 Qty In stock : 94
Price : 1.21 Price : 1.63
***************************** *****************************
Product ID : 8 Product ID : 2
Product Name : Island Oasis - Raspberry Product Name : Pork - Bacon,back Peameal
Qty In stock : 26 Qty In stock : 49
Price : 0.74 Price : 4.65
***************************** *****************************
Product ID : 3 Product ID : 6
Product Name : Lettuce - Romaine, Heart Product Name : Petit Baguette
Qty In stock : 38 Qty In stock : 14
Price : 3.35 Price : 2.39
***************************** *****************************
Product ID : 9 Product ID : 9
Product Name : Longan Product Name : Longan
Qty In stock : 67 Qty In stock : 67
Price : 2.26 Price : 2.26
***************************** *****************************
Product ID : 6 Product ID : 3
Product Name : Petit Baguette Product Name : Lettuce - Romaine, Heart
Qty In stock : 14 Qty In stock : 38
Price : 2.39 Price : 3.35
***************************** *****************************
Product ID : 2 Product ID : 8
Product Name : Pork - Bacon,back Peameal Product Name : Island Oasis - Raspberry
Qty In stock : 49 Qty In stock : 26
Price : 4.65 Price : 0.74
***************************** *****************************
Product ID : 5 Product ID : 1
Product Name : Sauce - Ranch Dressing Product Name : Foam Dinner Plate
Qty In stock : 94 Qty In stock : 70
Price : 1.63 Price : 1.21
***************************** *****************************
Product ID : 7 Product ID : 10
Product Name : Sweet Pea Sprouts Product Name : Broom - Push
Qty In stock : 98 Qty In stock : 6
Price : 3.29 Price : 1.09
***************************** *****************************
Product ID : 11 Product ID : 4
Product Name : Wire Product Name : Brocolinni - Gaylan, Chinese
Qty In stock : 50 Qty In stock : 90
Price : 6.6 Price : 4.53
***************************** ******************************

Program to carete the database in my sql

package JdbcConnectionDemo;
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 void main(String[] args) {
try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query="CREATE DATABASE Employee";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");
ps.executeUpdate();

System.out.println("Database created successfully!!!");

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}
}}
O/P-
connecting to database
creating connection
Executing query
Database created successfully!!!

Program to Drop the database in my sql :

package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sql_store", "root",
"123123azAZ@");

String query="DROP DATABASE Employee";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");

ps.executeUpdate();
System.out.println("Database Drop successfully!!!");
con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();}}}

Creating a table in employee DATABASE


package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

String query="CREATE TABLE BasicInfo"+ "(id INT NOT NULL,"


+ " first_name VARCHAR(25), last_name VARCHAR(25),"
+ "email_id VARCHAR(75), phone INT)";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");

ps.executeUpdate();

System.out.println("Table created successfully!!!");


//ResultSet rs=ps.executeQuery();

//rs.close();

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
O/p-
connecting to database
creating connection
Executing query
Table created successfully!!!

Program for drop table in my sql

package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) {
try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

String query="DROP TABLE SALARY ";

System.out.println("creating connection");

PreparedStatement ps=con.prepareStatement(query);

System.out.println("Executing query");
ps.executeUpdate();

System.out.println("Table Drop successfully!!!");

con.close();
ps.close();
}catch (SQLException e) {
e.printStackTrace();}}}
O/P- connecting to database
creating connection
Executing query
Table Drop successfully!!!

Program to insert Batch of query (multiple row) in Mysql using Statement


package JdbcConnectionDemo;
🙂
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

con.setAutoCommit(false);

String query="INSERT INTO basicinfo VALUES(7, 'Ravi', 'karhade',


'raviraj.karhade@gmail.com', 7776899)";
String query1="INSERT INTO basicinfo VALUES(8, 'Anju', 'karhade',
'anjali.karhade@gmail.com', 8888888)";
String query2="INSERT INTO basicinfo VALUES(9, 'Piyu', 'karhade',
'piyukarhade@gmail.com', 9999999)";

System.out.println("creating connection");

Statement s=con.createStatement();

System.out.println("Executing query");
s.addBatch(query);
s.addBatch(query1);
s.addBatch(query2);

int batch[]=s.executeBatch();

con.commit();
for(int i=0; i<=batch.length; i++) {
System.out.println("I am Updating value in database, I
updated this : "+batch[i]);
}

System.out.println("All entry updated successfully!!!");


con.close();
s.close();
}catch (SQLException e) {

e.printStackTrace();
}
}
}
O/p- connecting to database
creating connection
Executing query
I am Updating value in database, I updated this : 1
I am Updating value in database, I updated this : 1
I am Updating value in database, I updated this : 1

Program to insert Batch() with multiple values by using PrepareStatement() in SQL


package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcDemo {

public static void main(String[] args) {

try {
System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

con.setAutoCommit(false);

String query="INSERT INTO basicinfo VALUES(?, ?, ?, ?, ?)";

System.out.println("creating connection");

PreparedStatement s=con.prepareStatement(query);

System.out.println("Executing query");

s.setInt(1, 12);
s.setString(2, "Sophia");
s.setString(3, "Davis");
s.setString(4, "sophia.davis@example.com");
s.setString(5, "5557891234");

s.addBatch();

int batch[]=s.executeBatch();

con.commit();
for(int i=0; i<=batch.length; i++) {
System.out.println("I am Updating value in database, I updated
this : "+batch[i]);
}

System.out.println("All entry updated successfully!!!");

con.close();
s.close();
}catch (SQLException e) {

e.printStackTrace();
}}}
O/P-connecting to database
creating connection
Executing query
I am Updating value in database, I updated this : 1

Program to store the file in database 👍


package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
/**
* @param args
*/
public static void main(String[] args) {
String fileToStore = "E:\\Documents/ravipic.jpg";

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

fileInputStream fileInputStream = new fileInputStream(fileToStore);


byte[] fileData = new byte[fileInputStream.available()];
fileInputStream.read(fileData);
fileInputStream.close();

String query="INSERT INTO ephotos VALUES(?)";

System.out.println("creating connection");

PreparedStatement s=con.prepareStatement(query);
s.setBytes(1, fileData);

System.out.println("Executing query");

s.executeUpdate();

System.out.println("All entry updated successfully!!!");


con.close();
s.close();
}catch (SQLException e) {

e.printStackTrace();
}
}
}

Program for transaction management by using con.setAutoCommit(false),


con.commit(), con.rollback()
package JdbcConnectionDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcDemo {

public static void main(String[] args) {

try {

System.out.println("connecting to database");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root",
"123123azAZ@");

con.setAutoCommit(false);

String query1="INSERT INTO basicinfo VALUES(16, 'Shiv', 'guru',


'shivtej.guru@gmial.com', 9638527)";
String query2="INSERT INTO basicinfo VALUES(17, 'Siya', 'gupta',
'siya.gupta@gmial.com', 7418529)";
String query3="INSERT INTO basicinfo VALUES(18, 'tiyu', 'desh',
'piyu.desh@gmial.com', 8527419)";

Statement s=con.createStatement();

System.out.println("creating connection");

System.out.println("Executing query");
s.executeUpdate(query1);
s.executeUpdate(query2);
s.executeUpdate(query3);

con.commit();

System.out.println("All entry inserted successfully!!!");

con.rollback();

con.close();

s.close();

}catch (SQLException e) {
e.printStackTrace();
}
}
}
o/p- connecting to database
creating connection
Executing query
All entry inserted successfully!!!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy