Establishing JDBC Connection in Java
Establishing JDBC Connection in Java
Before establishing a connection between front end i.e your Java Program and back
end i.e the database we should learn what precisely a JDBC is and why it came to
existence.
What is JDBC ?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC
( Open Database Connectivity ). JDBC is an standard API specification developed in
order to move data from frontend to backend. This API consists of classes and
interfaces written in Java. It basically acts as an interface (not the one we use in
Java) or channel between your Java program and databases i.e it establishes a link
between the two so that a programmer could send data from Java code and store it
in the database for future use.
Why JDBC came into existence ?
As previously told JDBC is an advancement for ODBC, ODBC being platform
dependent had a lot of drawbacks. ODBC API was written in C,C++, Python, Core
Java and as we know above languages (except Java and some part of Python )are
platform dependent . Therefore to remove dependence, JDBC was developed by
database vendor which consisted of classes and interfaces written in Java.
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is sql query of the type String
5.Close the connections
So finally we have sent the data to the specified location and now we are at the
verge of completion of our task .
By closing connection, objects of Statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.
Example :
con.close();
Implementation
importjava.sql.*;
importjava.util.*;
class Main
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";
//Entering the data
Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();
//Inserting data using SQL query
String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//Reference to connection interface
con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
Output –