JDBC defines a universal interface for accessing various relational databases. The main function of JDBC API( java database connectivity application programming interface) is to provide methods for developer to prepare and send SQL statements to database server and fetch the results in database independent manner.
it involes the following steps-
- establish a DB connection.
- send SQL statement to the DB server.
- fetch the result from server and process as required.
- the DriverManager class.
- the Connection class.
- the Statement class.
- the ResultSet class.
to connect your java program to MySql server- the first requirement is to install MySql Connector/J driver.
the driver may downloaded from http://dev.mysql.com/downloads.
goto netbeans->tools->libraries and add the mysql connector/j .jar you just downloaded using add jar folder button.
to establish a connection.
- import the required packages for connection.(Step 1)
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
- import java.sql.ResultSet;
- or you may use just one statement in place of importing individual classes-
- import java.sql.*;
- Register the jdbc driver as given below. use one of the driver given below.(Step 2)
- java.sql.Driver or
- com.mysql.jdbc.Driver
or
Class.forName(“com.mysql.jdbc.Driver”);
- open a connection(3rd step)
String uid=”root”;
String pwd=”toor”;
String db_url=”jdbc:mysql://localhost:3305/stu”
Connection con=DriverManager.getConnection(db_url,uid,pw);
Statement stmt=con.createStatement();
- write sql query and execute.(4th step)
ResultSet rs=stmt.executeQuery(query);
- Retrieve data from result set (5th step)
String clas=rs.getString(“clas”);
String sec=rs.getString(“section”);
now process as many recordsusing a loop.
and finally cleanup and release the connection
rs.close();
stmt.close()
con.close();

Comments