Share on Google+Share on Google+

Insert a row in 'Mysql' table using JSP Code

In this section, we will discuss about how to insert data in Mysql database using JSP code.

Insert a row in 'Mysql' table using JSP Code

In this section, we will discuss about how to insert data in Mysql database using JSP code.

Query for creating database table :

create database ankdb;

create table stu_info (
ID int not null auto_increment,
Name varchar(20),
City varchar(20),
Phone varchar(15),
primary key(ID)

NOTE : Download Mysql connector.jar file from--

And paste it in " jre\ lib\ ext " folder of Java. This file acts as connector between your Tomcat server & Mysql database Table.

Code to insert row in Mysql table :


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

<%@ page import="*" %>



<TITLE>Navigating in a Database Table </TITLE>


<BODY bgcolor="#ffffcc">

<font size="+3" color="red"><br>Welcome Guest !</font>

<FORM action="databaseinsertion.jsp" method="get">

<TABLE style="background-color: #ECE5B6;" WIDTH="30%" >


<TH width="50%">Name</TH>

<TD width="50%"><INPUT TYPE="text" NAME="name"></TD>



<TH width="50%">City</TH>

<TD width="50%"><INPUT TYPE="text" NAME="city"></TD>



<TH width="50%">Phone</TH>

<TD width="50%"><INPUT TYPE="text" NAME="phone"></TD>




<TD width="50%"><INPUT TYPE="submit" VALUE="submit"></TD>




String name = request.getParameter("name");

String city = request.getParameter("city");

String phone = request.getParameter("phone");

String connectionURL ="jdbc:mysql://";

Connection connection = null;

PreparedStatement pstatement = null;


int updateQuery = 0;

if(name!=null && city!=null && phone!=null){

if(name!="" && city!="" && phone!="") {

try {

connection = DriverManager.getConnection(connectionURL,"root","root");

String queryString = "INSERT INTO stu_info(Name,City,Phone) VALUES (?, ?, ?)";

pstatement = connection.prepareStatement(queryString);

pstatement.setString(1, name);

pstatement.setString(2, city);

pstatement.setString(3, phone);

updateQuery = pstatement.executeUpdate();

if (updateQuery != 0) { %>


<TABLE style="background-color: #E3E4FA;" WIDTH="30%" border="1">

<tr><th>Data is inserted successfully in database.</th></tr>





catch (Exception ex) {

out.println("Unable to connect to batabase.");


finally {











After inserting row in table ,the following message will display  :

Download Source Code



Posted on: June 25, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.