Insert a row in 'Mysql' table 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.

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--

http://www.oracle.com/technology/products/database/sql_developer/files/thirdparty.htm

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 :

databaseinsertion.jsp

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

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

<HTML>

<HEAD>

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

</HEAD>

<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%" >

<TR>

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

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

</tr>

<TR>

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

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

</tr>

0

<TR>

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

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

1

</tr>

<TR>

2

<TH></TH>

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

</tr>

3

</TABLE>

<%

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

4

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

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

String connectionURL ="jdbc:mysql://192.168.10.13:3306/ankdb";

5

Connection connection = null;

PreparedStatement pstatement = null;

6

Class.forName("com.mysql.jdbc.Driver").newInstance();

int updateQuery = 0;

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

7

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

try {

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

8

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

pstatement = connection.prepareStatement(queryString);

pstatement.setString(1, name);

9

pstatement.setString(2, city);

pstatement.setString(3, phone);

updateQuery = pstatement.executeUpdate();

0

if (updateQuery != 0) { %>

<br>

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

1

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

</table>

<%

2

}

}

catch (Exception ex) {

3

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

}

finally {

4

pstatement.close();

connection.close();

}

5

}

}

%>

6

</FORM>

</body>

</html>

7

OUTPUT :

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

8

Download Source Code

Ads