Java Project JSP JDBC Java Program Core Java Demo MORE

How to Create table in MySql using JSP code


For insert data in MySQL using JSP first we have to create a table in data base.

The INSERT INTO statement is used to insert new data to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.

For creating table the SQL query is:

SQL Query

CREATE TABLE users
(
id int NOT NULL AUTO_INCREMENT,
first_name varchar(50),
last_name varchar(50),
city_name varchar(50),
email varchar(50),
PRIMARY KEY (id)
); 

Here we using 2 files for insert data in MySQL:

  • index.html:for getting the values from the user
  • process.jsp:A JSP file that process the request

index.html

<!DOCTYPE html>
<html>
<body>
<form method="post" action="process.jsp">
First name:<br>
<input type="text" name="first_name">
<br>
Last name:<br>
<input type="text" name="last_name">
<br>
City name:<br>
<input type="text" name="city_name">
<br>
Email Id:<br>
<input type="email" name="email">
<br><br>
<input type="submit" value="submit">
</form>
</body>
</html>

process.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
{
         Class.forName("com.mysql.jdbc.Driver");
           Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
           Statement st=conn.createStatement();
           int i=st.executeUpdate("insert into users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')");
        out.println("Data is successfully inserted!");
        }
        catch(Exception e)
        {
        System.out.print(e);
        e.printStackTrace();
        }
 %>

Output

First name:

Last name:

City name:

Email Id: