In this section we will discuss how can we insert a data into the table.
Insert data into table java servlet
In this section we will discuss how can we insert a data into the table.
In the given example I used the insert query statement for insert data into the table. Further since the executeUpdate("") returns an integer value if it updated the statement otherwise returns '0' if the SQL statement does not return anything, so I put it into the 'if' statement for verifying of its updation. Next I put the executeQuery statement into the ResultSet object for displaying the table contents.
Example :
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.DriverManager; public class InsertInTable extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); Statement stmt; Connection con; ResultSet rs; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:dataInsert"); stmt = con.createStatement(); int i = stmt.executeUpdate("insert into data values ('Bipul', 24)"); if (i != 0) { pw.println("Record has been inserted successfully<br>"); } else { pw.println("Inserting record get failure"); } rs = stmt.executeQuery("SELECT * FROM data"); pw.println("name\t age"); while (rs.next()) { pw.println("<br>" + rs.getString(1) + ",\t " + rs.getInt(2)); } rs.close(); stmt.close(); } catch (Exception e) { pw.println(e.getMessage()); } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>InsertInTable</display-name> <servlet> <servlet-name>InsertInTable</servlet-name> <servlet-class>InsertInTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>InsertInTable</servlet-name> <url-pattern>/InsertInTable</url-pattern> </servlet-mapping> </web-app>
Output :
When you will execute the above example you will find the following output :
After executing this example database also be updated by the new value as :
[ 0 ] Comments