Loading
View RSS Feed

indies

The Best Way To Learn JDBC Programs Part 1

Rate this Entry
Code:
import java.sql.*;
import java.io.*;
class jdbc1
{
	public static void main(String args[])
	{
		Connection con;
		Statement stmt;
		ResultSet rs;
		String str;
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			
			con=DriverManager.getConnection("jdbc:odbc:harsh");
			System.out.println("Connection successful");
			stmt=con.createStatement();
			rs=stmt.executeQuery("select * from student");
			while(rs.next())
			{
				str=rs.getString(1);
				System.out.println(str);
				
			}
		}catch(Exception ex)
		{}
		 
	}
}
explanation:-
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access.
JDBC helps you to write java applications that manage these three programming activities:
1.Connect to a data source, like a database
2.Send queries and update statements to the database
3.Retrieve and process the results received from the database in answer to your query


The first thing to do is to import the packages or classes you will be using in the new class. The classes in our examples all use the java.sql package (the JDBC™ API), which becomes available when the following line of code precedes the class definition:
import java.sql.*;

The star ( * ) indicates that all of the classes in the package java.sql are to be imported. Importing a class makes it visible and means that you do not have to write out the fully qualified name when you use a method or field from that class. If you do not include " import java.sql.*; " in your code, you will have to write " java.sql. " plus the class name in front of all the JDBC fields or methods you use every time you use them. Note that you can import individual classes selectively rather than a whole package. Java does not require that you import classes or packages, but doing so makes writing code a lot more convenient.
Java application calls the JDBC library. JDBC loads a driver which talks to the database.
We can change database engines without changing database code.


Loading a database driver,

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is "Class". Class is a class in java.lang package.

Code:
try { 
	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other driver
}
catch(Exception x){ 
	System.out.println( "Unable to load the driver class!" );
}

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection
with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.J

JDBC URL Syntax::
jdbc: <subprotocol>: <subname>




JDBC URL Example::


jdbc: <subprotocol>: <subname>
•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We're using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver
.try{
Connection dbConnection=DriverManager.getConnection(url,"logi nName","Password")
}
catch( SQLException x ){
System.out.println( "Couldn't get connection!" );
}


Creating a jdbc Statement object,
Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.

Code:
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements

Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.
Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements
.

Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.
Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

Statement interface defines methods that are used to interact with database via the execution
of SQL statements.
The Statement class has three methods for executing statements:
Code:
executeQuery(), executeUpdate(), and execute().
For a SELECT statement,
the method to use is executeQuery .
For statements that create or modify tables, the method to use is executeUpdate.
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate.
execute() executes an SQL statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.


PREPARED STATEMENT EXAMPLE
Code:
import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 

public class PreparedStatementExample {
 public static void main(String[] args) { 
 try { 
 /** Loading the driver*/ 
Class.forName("com.mysql.jdbc.Driver");
 /** Getting Connection*/ 
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); 
  /** Creating Statement*/ 
 PreparedStatement pst = con.prepareStatement("insert into visualbuilder(id,name)values(?,?)"); 
 pst.setInt(1,1);
 pst.setString(2,"VisualBuilder"); 
 int i= pst.executeUpdate();
System.out.println(i + " Record(s) Inserted"); 
 /** Closing the Connection*/ 
 pst.close(); 
  con.close();
 } catch (Exception e) { 
 e.printStackTrace();                                          }

}
 }
Output:-
Code:
1 Recored(s) inserted
Visit second part here :The Best Way To Learn JDBC Programs Part 2

Submit "The Best Way To Learn JDBC Programs Part 1" to Digg Submit "The Best Way To Learn JDBC Programs Part 1" to del.icio.us Submit "The Best Way To Learn JDBC Programs Part 1" to StumbleUpon Submit "The Best Way To Learn JDBC Programs Part 1" to Google

Updated 11-23-2011 at 09:32 PM by angad

Categories
Java , Web Design

Comments

  1. Deena's Avatar
    Dude, right on there btrhoer.



Disclaimer: Users of techforum4u.com are responsible for ensuring that any material they post (article, blog posts, images or other mulitimedia content) does not violate or infringe upon the copyright, patent, trademark, or any personal or proprietary rights of any third party, and is posted with the permission of the owner of such rights.Anyone who violates these rules may have their access privileges removed without warning.