What are different steps to connect any java application with the database in java using JDBC used in JDBC? Write down a small program showing all steps.
There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:
1. Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
Syntax of for Name() method
public static void forName(String className) throws ClassNotFound Exception
Example to register the Driver class
Class.for Name("com.mysql.jdbc.Driver ")
2.Creating connection
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax
public static Connection getConnection(db_url)or,
public static Connection getConnection(db_url, user_name, password)
Example to establish connection with the mySQL database
Connection con=DriverManager.getConnection("jdbc: mysql://Localhost/emp", "root", "arjun");
3.Creating a statement
The createStatement() method of the Connection interface is used to create a statement. The object of the statement is responsible to execute queries with the database.
Syntax
public Statement createStatement()
Example to create the statement object
Statement stmt=con.createStatement();
4. Executing queries
Once we have created a Statement object, we can use it to execute a SQL statement with one of its three execute methods.
a) boolean execute(String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. This method is used to execute SQL DDL statements or when we need to use truly dynamic SQL.
b) int execute Update(String SQL): Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which we expect to get a number of rows affected for example, an INSERT, UPDATE, or DELETE statement.
Example to execute query
ResultSet rs=stmt. executeQuery("select from emp");
fi ResultSet executeQuery(String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as we would with a SELECT statement.
Once the ResultSet is obtained, we can iterate through it as below:
while(rs.next())
{
System.out.println(rs.getInt (1) +""+rs.getString(2));
}
5. Closing connection
By closing the connection, the object statement and ResultSet will be closed automatically. The close method of the Connection interface is used to close the connection.
Syntax
public void close()
Example to close connection
con.close();
Complete Example
//STEP 1. Import required packages
import java.sql.*;
Public class ConnectDB
{
static final String JDBC_DRIVER = static final String DB_URL = "com.mysql.jdbc.Driver"; "jdbc:mysql://localhost/emp";
public static void main(String[] args)
{
Connection conn = null;
try
{
Statement stmt = null;
//STEP 2: Register JDBC driver
Class. for Name("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn =DriverManager.getConnection (DB_URL, "root", "arjun");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement ();
String sql;
sql = "SELECT eid, age, Fname, Lname FROM employees";
ResultSet rs = stmt.executeQuery (sql);
//STEP 5: Extract data from result set
while(rs.next())
{
//Retrieve by column name int id rs.getInt ("eid");
int age= rs.getInt("age");
String first = rs.getString("Fname"); String last = rs.getString("Lname");
//Display values
System.out.print("ID: + id);
System.out.print(", Age: + age);
System.out.print(", First Name: " + first);
System.out.println(", Last: Name " + last);
}
//STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close();
}
catch(SQLException se)
{
//Handle errors for JDBCINT se.printStackTrace();
}
catch (Exception e)
{
//Handle errors for Class.forName e.printStackTrace();
}
System.out.println("Goodbye!");
}//end main
}
Comments
Post a Comment