Connection with MySQL Database using JSP

Google Sponsored Links

The below code explains how to make connection with MySQL database using JSP.
This is not the production code, its just for practice. You can modify according to your need.


<%@page contentType="text/html" pageEncoding="UTF-8"%>

Creating Table in DB using JSP

<%@ page import=”java.sql.*” %>
<%@ page import=”*” %>

        <%                     /* Create string of connection url within specified                     format with machine name, port number                     and database name. Here machine name id localhost                     and database name is usermaster. */                     String connectionURL = “jdbc:mysql://localhost:3306/stack”;                     // declare a connection by using Connection interface                     Connection connection = null;                     // declare object of Statement interface that is used for                     // executing sql statements.                     Statement statement = null;                     try {                         // Load JBBC driver “com.mysql.jdbc.Driver”.                         Class.forName(“com.mysql.jdbc.Driver”);                       /* Create a connection by using getConnection() method                         that takes parameters of string type connection url, user                         name and password to connect to database. */                         connection = DriverManager.getConnection(connectionURL, “root”, “”);                         /* createStatement() is used for create statement object                         that is used for sending                         sql statements to the specified database. */ System.out.println(“hello”);                         statement = connection.createStatement();                         // sql query to retrieve values from the secified table.                         String QueryString = “create table user_master(id int not null auto_increment,name ” + “varchar(25),city varchar(20), primary key(id))”;                         // execyteUpdate() mothod execute specified sql query.                         statement.executeUpdate(QueryString);                         out.print(“QueryString”);         %>

Google Sponsored Links
        <%      } catch (Exception ex) {         ex.printStackTrace(); %>
                    Congratulations !
                    Table of specified name is created successfully.
            <%             }             %>
                        back to home page



Google Sponsored Links