JavaBeginner
JavaBeginner

Reputation: 115

Accessing Database using JSP

I am learning JSP and I want to create a table in mysql using JSP. I have the following code.

    <%@ page contentType="text/html;charset=UTF-8" %>
    <%@ page errorPage="error.jsp" %>
    <%@ page import="java.sql.*" %>

    <html>
    <head>
    <title>MySQL Database creation</title>
    <style>
      { font-size: 12px; font-family: Verdana }
    </style>
    </head>
    <body>

    <h2>Creation of a books database</h2>

    <jsp:declaration>

    Statement stmt;
    Connection con;
    String url = "jdbc:mysql://localhost:3306/";

    </jsp:declaration>

    <jsp:scriptlet><![CDATA[

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(url, "root", ""); 

    stmt = con.createStatement();
    stmt.executeUpdate("CREATE DATABASE books");
    con.close();

    ]]></jsp:scriptlet>

    </body>
    </html>

and my error.jsp page is

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

   <html>
   <head>
   <title>Error page</title>
   <style>
     { font-size: 12px; font-family: Verdana }
   </style>
   </head>
   <body>
   <h2>Error occured!</h2>
   <p>Message 
   <jsp:expression> 
        exception.getMessage() 
   </jsp:expression>
   </p>

   </body>
   </html>

When I run it, it is getting redirected to error page and getting the output as below:

Error occured! Message com.mysql.jdbc.Driver

Where am I going wrong?

Upvotes: 2

Views: 5816

Answers (3)

shashikumar
shashikumar

Reputation: 1

friend after downloading your mysqlconnector you should provide the mysqlconnector path to jdk.

Upvotes: 0

Ganesh Rengarajan
Ganesh Rengarajan

Reputation: 2006

Use this one

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page errorPage="error.jsp" %>
<%@ page import="java.sql.*" %>

<html>
<head>
<title>MySQL Database creation</title>
<style>
  { font-size: 12px; font-family: Verdana }
</style>
</head>
<body>

<h2>Creation of a books database</h2>

<jsp:declaration>

Statement stmt;
Connection con;
String url = "jdbc:mysql://localhost:3306/your database name";

</jsp:declaration>

<jsp:scriptlet><![CDATA[

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, "root", ""); 

stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE `test`.`sample` (`id` TINYINT UNSIGNED), `name` VARCHAR (50)");
con.close();

]]></jsp:scriptlet>

Upvotes: 0

Ganesh Rengarajan
Ganesh Rengarajan

Reputation: 2006

Jsp for front end so please avoid database code here

solution for you

add jar file download

mysqlconnecter.jar

Upvotes: 1

Related Questions