[an error occurred while processing this directive]

Connect JSP with mysql


In this example we will show you how to connect to MySQL database from your JSP code. First, you need to create database and then write jsp code to connect jsp to database.

1. Create a database: 

First create a database named usermaster in mysql. Before running the jsp code you need to paste mySqlConnector.jar in lib directory of jdk.

mysql> create database usermaster;
(This query create database in my sql command prompt)

2. Connect JSP with mysql:  

Here is the jsp code.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 

<%@ page import="java.sql.*" %> 
<%@ page import="java.io.*" %> 

<title>Connection with mysql database</title> 
<h1>Connection status </h1>
try {
/* 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/usermaster"; 

// declare a connection by using Connection interface 
Connection connection = null; 

// Load JBBC driver "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", "root");

// check weather connection is established or not by isClosed() method 
<font size="+3" color="green"></b>
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
catch(Exception ex){
<font size="+3" color="red"></b>
out.println("Unable to connect to database.");

Output of the program when connection is established with specified mysql database :

Output of the program when unable to connect to specified MySQL database :

Download source code


[an error occurred while processing this directive]