Posted on 2017-12-25 05:32:09 by mkshine65
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.
For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity.
In this example we are using MySql as the database. So we need to know following informations for the mysql database:
Let's first create a table in mysql database.
For that we have to create a database using our MySQL Prompt. If already database is available skip this step.
create database demo; // demo is the database name. |
Then change to our working database.
use demo; // Changing to database Demo. |
Then Create table.
create table student(name varchar(50),email varchar(100)); // creating a stable. |
import java.sql.*; public class JDBC { public static void main(String[] args) throws SQLException { Connection myConn = null; Statement myStmt = null; ResultSet myRs = null; try { // 1. Get a connection to database. Class.forName("com.mysql.jdbc.Driver"); myConn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/demo","root","root"); myStmt = myConn.createStatement(); String sql = "INSERT INTO students VALUES ('xxx','[email protected]')"; myStmt.executeUpdate(sql); myRs = myStmt.executeQuery("select * from students"); // 4. Process the result set while (myRs.next()) { System.out.println(myRs.getString("name") + ", " + myRs.getString("email")); } } catch (Exception exc) { } { { } if (myStmt != null) { } if (myConn != null) { } |