Insert a row in 'Mysql' table using JSP Code

Ads
 

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>

<TR>

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

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

</tr>

<TR>

<TH></TH>

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

</tr>

</TABLE>

<%

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

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

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

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

Connection connection = null;

PreparedStatement pstatement = null;

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

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) { %>

<br>

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

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

</table>

<%

}

}

catch (Exception ex) {

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

}

finally {

pstatement.close();

connection.close();

}

}

}

%>

</FORM>

</body>

</html>

OUTPUT :

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

Download Source Code

Ads

Ads