Conduct some research to find out how a Java-based application can be connected to a database. Provide some brief code snippets and annotate the code.
a Java-based application can be connected to a database using Java Database Connectivity(JDBC).
to establish a connection to database through jdbc first you
will have to load jdbc driver using one of the two methods given
below.
Class.forName() : Here we load the driver’s class file into memory
at the runtime. to load oracle driver use
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver())
After loading the driver, establish connections using :
Connection con =
DriverManager.getConnection(url,user,password)
url : Uniform Resource Locator. It can be created as follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe” where xe is
sid ofthe oracle database you are trying to connect
once we have connection we can use sql queries to manipulate data
in the database.
The JDBCStatement, CallableStatement, and PreparedStatement
interfaces define the methods that enable you to send SQL commands
and receive data from your database.
for example to insert a record use below code snippet. sql variable holds the query to actual insertion into a table
Statement st = con.createStatement();
String sql = "INSERT INTO Customers (CustomerName,
ContactName)
VALUES ('Cardinal', 'Tom B. Erichsen')";
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
finally when you are done talking to database you can close the
connection
con.close();
Conduct some research to find out how a Java-based application can be connected to a database....