Tuesday, October 11, 2011

JDBC Connection

JDBC(Java Database Connectivity)
It defines interface and classes for writting database application in java by making database connection.

Steps:
Before you create java jdbc connection to the database you must import suitable package as import java.sql.*;

1.Loading DataBase Driver.
We load the driver class by calling Class.forName(String ClassName) method in class.
For jdbc-odbc driver:-"sun.jdbc.odbc.JdbcOdbcDriver"
for mysql :-"com.mysql.jdbc.Driver"
2.Creating JDBC Connection.
The JDBC Driver Manager class define objects which can connect java application to JDBC Driver.
getConnection() is used to establish a connection to data base.It need username ,password, and JDBC URL to establish connection.
Connection con = DriverManager.getConnection(url,"username","password");
3.Creating a JDBC Statement Object
Once a connection is obtained we can interact with data base.To execute SQL Statement we need create Stetement method
Statement st = con .createStatement();
4.Executiong SQL Statement with Statement object and returning a jdbc resultset
statement class has 3 method for executing statement
a)executeQuery-select statement
b)executeUpdate-To modify table
c)execute-Execute sql statement.

ResultSet
It provide access to a table of database.tables rows are reterieved in sequence.

next()
This method is used to successivelly step through rows of tabular result.

Java JDBC Connection Example.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.io.IOException;

Connection con=null;
String url="jdbc:mysql://localhost:3306/"; //For my sql
String db ="vikashtest"; //Database name
String user="root"; //user name
String pass="vikash"; //password

try {
Class.forName("com.mysql.jdbc.Driver"); //Loading DataBase Driver
con=DriverManager.getConnection(url+db , user ,pass); //Creating connection with database
Statement st = con.createStatement(); //creating statement object
st.execute("Query"')");
String data=(column of table);

st.close();
}
catch(Exception e)
{
e.printStackTrace();
}

Note:-Create lib folder inside web-inf folder and keep jar for sql server in it .Then build path for it.

Example to connect to HTML and database

No comments:

Post a Comment