Share on Google+Share on Google+

karabo lizzy medupe
database
1 Answer(s)      5 years and 11 months ago
Posted in : JSP-Servlet

the code for initializing the database connection

Ads

View Answers

May 11, 2011 at 5:40 PM


A servlet must have a MySQL 'Driver' to connect to a MySQL database. The driver we use is the class "com.mysql.jdbc.Driver" which is found in the 'mysql-connector-java-5.0.4-bin.jar'. this file is to be copied into the lib of apache tomcat and use the following code:

import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection extends HttpServlet {
  public void service(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Servlet JDBC</title></head>");
    out.println("<body>");
    out.println("<h1>Servlet JDBC</h1>");
    out.println("</body></html>");  
    // connecting to database
    Connection con = null;    
    Statement stmt = null;
    ResultSet rs = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      con =DriverManager.getConnection 
      ("jdbc:mysql://localhost:3306/example","root","root");
      stmt = con.createStatement();
      rs = stmt.executeQuery("SELECT * FROM servlet");
      // displaying records
      while(rs.next()){
        out.print(rs.getString(1));
        out.print("\t\t\t");
        out.print(rs.getString(2));
        out.print("<br>");
      }
    } catch (SQLException e) {
 throw new ServletException("Servlet Could not display records.", e);
      } catch (ClassNotFoundException e) {
        throw new ServletException("JDBC Driver not found.", e);
      } finally {
        try {
          if(rs != null) {
            rs.close();
            rs = null;
          }
          if(stmt != null) {
            stmt.close();
            stmt = null;
          }
          if(con != null) {
            con.close();
            con = null;
          }
        } catch (SQLException e) {}
      }
      out.close();
    }
  }

For more information, visit the following link:

Servlet Tutorials










Related Tutorials/Questions & Answers:
database
database  database
database
database  database application
Advertisements
database
database  the code for initializing the database connection
database
database  i want to let the user select the name of database and then delete that database.......im doing project in swings netbeans
database
database  use of hyperlink to show the data from database
database
database  i need to insert time in my database. i need a code to insert time in my database. its very urgent
database
database  tell me use about database and give me a small program.   It is secure and can easily be accessed, managed, and updated. Moreover... links: Connect JSP with database Mysql Connect Java with database Mysql
database
database  tell me use about database and give me a small program.   It is secure and can easily be accessed, managed, and updated. Moreover... links: Connect JSP with database Mysql Connect Java with database Mysql
database
database  tell me use about database and give me a small program.   It is secure and can easily be accessed, managed, and updated. Moreover... links: Connect JSP with database Mysql Connect Java with database Mysql
database
database  im doing my project in netbeans swings...wn a user wants to create a database from the gui...i want to display an error msg if a database with that name already exists and if it does not exist new database should
Database
Database  from java code i have to retrieve some data from a database, which is present in a different timezone. Scenario :- My database... in database timezone is 9PM 15APR2012. I want to retrieve something from database
Database
Database  I am working in jsf2.Fro a demo i created database in ms access.no wi want to retrive a record from database for a particular data.I need help as I am stuck
Database
Database  How to represent data from database in a tree?   Please visit the following link: Retrieve data from database in tree using Java Swing
DATABASE
DATABASE  How can i get combo box values from database?? or how can i get values in the drop down menu of the html which is similar to dat of combo box in java - from database
database
database  I wanted to know if it is possible to establish database connection on a remote pc with mysql using java swings from netbeans and then create a database on the remote pc.... Kindly help me
database
database  I wanted to know if it is possible to create a database in mysql by letting the user enter the name of the database in swing gui..im doing my project in netbeans...Thank You
Database
Database  Can i get a code for database connectivity Myeclipse 3.3 to MySql manager 2005
database
database  hi i want to develop one patient database can any one provide me the guide
database
database  sir.. how we can uplaod the database in the data file(ms access)please send me a solution
database
database  how we ca upload the data in the database file(ms access
database
database  dateofbirth is not save into the database while i am enter from html browser.it shows as null.whats the reason
DATABASE
DATABASE  I can't send different information from different form into a single table in my database
database
database  Im doing my project in java swings...netbeans I wanted java source code to establish connection to postgresql_8.1 using jdbc and create a user defined database and a table in that database and insert values Plz help me
database
database  In my project,i want the user to specify the name of the database he wants to create in mysql and then also the name of the table along with the column names he wants in that database....Im doing my project in netbeans
database
database  In my project where u helped me to display the databases present im mysql database on the Jlist and then the respective tables in that database on another jlist and then the column names on another jlist I dont want
database
database  i need optimised searching algorithm to retrieve the data from the database and optimised ranking algorithm to display the reults into the user
database
database  Can you please help me to establish database connection to ms sql 2000 from java swing in netbeans
database
the names of the databases present in mysql database on a Jlist that is already present on the gui and when the user selects a particular database,the tables present under that database should be displayed on another Jlist which is present
database
database  I want to let the user select one of the database type... give the name of the database name that he want to create in a textfield... database..im doing my project in java swings.....netbeans Kindly help me ThankYou
Database
Database   select * from student i am not asking this.i am asking about that the command line code like create table student(..........) like this way
Database
Database  In MYSQL database i m given as the email id as the char but i enter the email id it gives manually error.how can i recover that error   For email, use the data type varchar
Tutorials   
Java Spring Hibernate Struts Training fat image from db fat image from db fat image from db fat image from db unable to get value returned from javascript variable in page How to change image size before adding to mysql using jsp Design a registration.jsp page with input for user registration details Cart Quantity jsp servlet coding issue servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ? image pdf marking pdf marking Multiple image upload using JSP Read code from excel sheet and upload into database using JSP Student java about search engine Convert BLOB to PDF and save it to a location how to copy files from remote to local machine using SFTP SSL in java? Like Team viewer Socket and Servert -Jsp how to copy files from remote location to local using java? How To Store Multilple Images In MySQL database dynamically with image uploader and then retrieve them in image gallery using java how to create SOAP based web service in java? how to fetch data from mysql database table and draw a bar chart on that data using in jsp how to create users in LDAP using java? how to authenticate user using TIVOLI api in java? how to create users using IBM Tivoi API in jsp/servelet? Java/J2ee Please explain this code as many packages and classes are unknown to me .! how to download the uploaded folder files using jsp Login Query image is display from path of mysql database please reply the code to store dynamic fields in database? Reloading issue in jsp How to get Button Id ? calling one jap page from another jsp page login login Problem to get connection from DAO class to JDBC Page Loading Time Fix table's column's name row(1st row of the table) so that it does not move up when the table is scrolled up to view more rows below Sending hidden values

Ads

 
Advertisement null

Ads