This discussion is archived
2 Replies Latest reply: Jun 5, 2008 11:19 PM by 807591 RSS

Java code for DB connection

807591 Newbie
Currently Being Moderated
Make the servlet entry in web.xml
************************
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
FormDB</display-name>
<welcome-file-list>
<welcome-file>Form.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FormServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>


</web-app>

***************************


JavaCode for DB Connection
/*
Import JDBC core packages.
Following statement imports the java.sql package, which contains the JDBC core API.
*/
import java.sql.*;
import java.sql.DriverManager;

public class RetriveAllEmployees{
public static void main(String[] args) {
System.out.println("Getting All Rows from employee table!");
Connection con = null;
Statement stmt = null;
String url = "jdbc:oracle:thin:@localhost:1521:XE";
//String url = "jdbc:mysql://localhost:3306/";
// http://127.0.0.1:8080/apex/f?p=4550:11:2998641328164352::NO:::
// jdbc:oracle:thin:@<database host machine>:<port>:<SID>"
String db = "jdbc";
// String driver = "com.mysql.jdbc.Driver";

String driver ="oracle.jdbc.driver.OracleDriver";
String user = "system";
String pass = "oracle";
try{
Class.forName(driver);
System.out.println("Hi : Before");
con = DriverManager.getConnection(url, user, pass);
System.out.println("Hi : After connection");
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM employee");
System.out.println("Employee Name: " );
while (res.next()) {
String employeeName = res.getString("EMP_NAME");
System.out.println(employeeName );
}

String selectQuery = "INSERT INTO EMPLOYEE (EMP_ID,EMP_ADDRESS,EMP_NAME,EMP_MOBILE) VALUES ('3','HELLO','IPSITA','99013452')";
try {
stmt.executeQuery(selectQuery);
}
catch (Exception e)
{
e.printStackTrace();
}

con.close();
}
catch (ClassNotFoundException e){
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex.printStackTrace();
ex = ex.getNextException(); // For drivers that support chained exceptions
}
}
}
}